Js中toFixed()方法保留小数不精准的问题

toFixed() 方法可把 Number 四舍五入为指定小数位数的数字。

问题:部分特殊数值使用toFixed() 方法会出现转换不正确的情况,举个例子:

(3329.225).toFixed(2) = "3329.22";   //正常应该是“3329.23”

变化数值位数得到的小数也不稳定:

 

解决:使用Math.round(x)来进行数值转换

1. Math.round(x)中round() 方法可把一个数字舍入为最接近的整数。比如0.5 将舍入为 1,而 -0.5 将舍入为 0

 2. 对需要保留小数的转换,公式为:Math.round( 3329.225 * Math.pow(10,2) )  /  Math.pow(10,2); ( 3329.225表示要处理的数值,2表示要保留的小数位数) 

3. 回到上面的例子,使用Math.round( )转换后就获取正常的四舍五入的值了:

其中 Math.pow(10,2) = 100;

 

猜你喜欢

转载自www.cnblogs.com/stella1024/p/11855980.html
今日推荐