js计算舍入误差解决办法

原文链接:http://www.luyixian.cn/javascript_show_154162.aspx

1、起因:

返回结果是true。

2、原因:计算机的二进制实现和位数限制有些数无法有限表示。就像一些无理数不能有限表示,如 圆周率 3.1415926...,1.3333... 等。JS 遵循 IEEE 754 规范,采用双精度存储(double precision),占用 64 bit。

3、解决方法

(1)toFixed(),存在兼容性(chrome)

(2)比较稳妥方法(数字如果过大,也会有误差):

*JS 中能精准表示的最大整数是 Math.pow(2, 53),十进制即 9007199254740992。  大于 9007199254740992 的可能会丢失精度

function round(num,d){

//Step1:将num放大10的d次方倍

num*=Math.pow(10,d);

//Step2:对num四舍五入取整

num = Math.round(num);

//Step:返回num缩小10的d次方倍,获得最终结果

return num/Math.round(10,d);

}

console.log(round(123.456)); //123.46

猜你喜欢

转载自www.cnblogs.com/LChenglong/p/12108273.html