码迷,mamicode.com
首页 > Web开发 > 详细

js浮点数运算出现误差解决方案

时间:2017-11-09 11:28:59      阅读:283      评论:0      收藏:0      [点我收藏+]

标签:出现   [1]   ase   const   解决方案   strip   add   logs   git   

1.数据展示类(使用 toPrecision 凑整并 parseFloat 转成数字后再显示)

parseFloat(1.4000000000000001.toPrecision(12)) === 1.4 // True 

封装成方法如下:

function strip(num, precision = 12) { 
  return +parseFloat(num.toPrecision(precision)); 
}  

2.数据运算类(对于运算类操作,如 +-*/,就不能使用 toPrecision 了。正确的做法是把小数转成整数后再运算)

以加法为例:

function add(num1, num2) { 
  const num1Digits = (num1.toString().split(‘.‘)[1] || ‘‘).length; 
  const num2Digits = (num2.toString().split(‘.‘)[1] || ‘‘).length; 
  const baseNum = Math.pow(10, Math.max(num1Digits, num2Digits)); 
  return (num1 * baseNum + num2 * baseNum) / baseNum; 
}  

 

js浮点数运算出现误差解决方案

标签:出现   [1]   ase   const   解决方案   strip   add   logs   git   

原文地址:http://www.cnblogs.com/sghy/p/7807798.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!