JS toFixed()填坑记录

1、在JS中四舍五入的函数 toFixed(n) , n为要保留的小数位数。 n为0~20,当n超过20的时候,JS会出错。

2、当截取小数点前一位是0时,输出结果可能会有所不同。

例如:var a = 0.145;

            a.toFixed(2);

结果为0.14;

解决办法:

var num = 0.145;

var fixNum = new Number(num+1).toFixed(2);

var fixedNum = new Number(fixNum - 1).toFixed(2);//四舍五入之后减1,再四舍五入一下  

alert(fixedNum);//弹出的数字就是正确的四舍五入结果啦 

猜你喜欢

转载自www.cnblogs.com/fengjingjing/p/10412484.html