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

Javascript“基本”求和小数错误结果

  •  1
  • fp007  · 技术社区  · 5 年前

    使用小数时,JS的简单数学会出错。

     console.log(.6+.6+.6) //1.7999999999999998
    

    一种可能的解决方案是将每个数字乘以一百万,然后除以一百万,但似乎根本没有效率。

    console.log(((.6*1000000)+(.6*1000000)+(.6*1000000))/1000000) //1.8
    

    在没有库的情况下,在JS中有没有用小数求和的“正确”方法?

    如果不是必须的,建议使用其他库,如 https://github.com/MikeMcl/bignumber.js/ https://github.com/MikeMcl/decimal.js/ https://mathjs.org/ 你推荐哪一个?

    目前,我认为最好只乘以1000000,然后再除以它,这样我就不必为“基本”操作安装整个模块了。。。但是JS中的基本操作不是基本的。

    1 回复  |  直到 5 年前
        1
  •  3
  •   Nikola Lukic    2 年前

    看看 Dealing with float precision in JS

    这是我的解决方案:

    console.log( parseFloat((.6+.6+.6).toFixed(2)) )
    
    // Or
    
    var a = 0.6;
    var b = 0.6;
    var c = 0.6;
    
    var R = parseFloat( (a + b + c).toFixed(2) );
    
    console.warn("Result :", R)
    
    
    // Final solution is method 
    // Array used for args[]
    
    function sumFloats (items) {
    
      var R = 0;
    
      for (var x = 0;x < items.length;x++) {
      console.warn(">>: ", items[x]);
      R += parseFloat( (items[x]).toFixed(2) );
      }
    
      R = parseFloat(R.toFixed(2));
      console.warn("Result from function: ", R);
      return R;
    
    }
    
    var a = 0.6;
    var b = 0.6;
    var c = 0.6;
    var ResultFromFunc = sumFloats ([0.6, 0.6, 0.6]);
    var ResultFromFunc2= sumFloats ([a, b, c]);

    到固定(dec)。将返回字符串,但格式良好,然后解析为浮点数以再次获取数字。

    更新:

    function sumFloats (items) {
    
      var R = 0;
    
      for (var x = 0;x < items.length;x++) {
      //console.warn(">>: ", items[x]);
      R += parseFloat( (items[x]).toFixed(2) );
      }
    
      R = parseFloat(R.toFixed(2));
      //console.warn("Result from function: ", R);
      return R;
    
    }
    
    // console.log( 33.4 + 33.3 + 33.3 ) // = 99.9999999 
    
    // test 
    var a = 33.4;
    var b = 33.3;
    var c = 33.3;
    
    console.log( "a + b + c = ",  a + b + c )
    console.log( "a + c + b = ",  a + c + b )
     
    console.log( "c + b + a = ",  c + b + a )  
    console.log( "c + a + b = ",  c + a + b )
    
    console.log( "b + c + a = ",  b + c + a )
    console.log( "b + a + c = ",  b + a + c )
    
    console.log( "sum -> ", sumFloats([a,b,c]) )
    console.log( "sum -> ", sumFloats([a,c,b]) )
    console.log( "sum -> ", sumFloats([c,b,a]) )
    console.log( "sum -> ", sumFloats([c,a,b]) )
    console.log( "sum -> ", sumFloats([b,c,a]) )
    console.log( "sum -> ", sumFloats([b,a,c]) )