在用js计算0.07*100时候竟然=7.000000000000001

 

 关于js失精算法你都遇到哪些,让我们一起来细数一下吧

console.log(0.07*100); // 7.000000000000001

console.log(0.1+0.2); // 0.30000000000000004 

 

事实上,0.1 + 0.2 这这样的 0.1000000000000000055511151231257827021181583404541015625 + 0.200000000000000011102230246251565404236316680908203125 = 0.3000000000000000444089209850062616169452667236328125

这也是造成计算失精的主要原因。

 

wiki:https://en.wikipedia.org/wiki/IEEE_floating_point#Basic_formats

 

oracle失精算法专栏:http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html

 

解决方案:

如果是取整数,我们可以这样:

 

Math.round((0.07*100))  

 

需要保留小数的,我们可以这样:

 

    parseFloat((0.07*100).toPrecision(12)) // = 7  
      
      
    parseFloat((0.01+0.02).toPrecision(12)) // = 0.03  

 

 

 

 

文章来源:http://qiaolevip.iteye.com/blog/2267471

 

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-10-15
  • 2022-01-01
  • 2021-09-06
  • 2021-09-22
猜你喜欢
  • 2022-12-23
  • 2021-09-19
  • 2022-01-24
  • 2022-12-23
  • 2022-12-23
  • 2021-06-17
相关资源
相似解决方案