代码之家  ›  专栏  ›  技术社区  ›  jantimon

Javascript计算错误

  •  4
  • jantimon  · 技术社区  · 14 年前

    * / ?

    在Chrome Firefox和Internet Explorer中,使用这些运算符有一个奇怪的行为:

    x1 = 9999.8
    x1 * 100 = 999979.9999999999
    x1 * 100 / 100 = 9999.8
    x1 / 100 = 99.99799999999999
    

    http://jsbin.com/ekoye3/

    我正试图用 parseInt ( x1 * 100 ) / 100 结果呢 9999.8 9999.79

    3 回复  |  直到 14 年前
        1
  •  7
  •   Community kfsone    7 年前

    那不是虫子。您可能想签出:

    x1 = 9999.8;                            // Your example
    console.log(x1 * 100);                  // 999979.9999999999
    console.log(x1 * 100 / 100);            // 9999.8
    console.log(x1 / 100);                  // 99.99799999999999
    
    x1 = 9999800;                           // Your example scaled by 1000
    console.log((x1 * 100) / 10000);        // 999980
    console.log((x1 * 100 / 100) / 10000);  // 9999.8
    console.log((x1 / 100) / 10000);        // 99.998
    
        2
  •  1
  •   Darin Dimitrov    14 年前

    你可以用这个 toFixed() 方法:

    var a = parseInt ( x1 * 100 ) / 100;
    var result = a.toFixed( 1 );
    
        3
  •  1
  •   Alexandre C.    14 年前

    You may want to check this . 如果你想计算代表金钱的数字,你应该数分并使用整数。