javascript中对小数进行四舍五入处理可以使用 tofixed() 方法,tofixed() 方法可把 number 四舍五入为指定小数位数的数字。
javascript中对小数进行四舍五入处理可以使用 tofixed() 方法,tofixed() 方法可把 number 四舍五入为指定小数位数的数字。
tofixed() 方法
把数字转换为字符串,结果的小数点后有指定位数的数字:
var num = 5.56789;var n=num.tofixed(2);
输出结果:
5.57
另外像 round()、floor()、ceil() 等都不能真正的四舍五入,有精度问题。下面我们再来了解一下javascript的round()方法对小数是如何处理的?
round() 方法
round() 方法可把一个数字舍入为最接近的整数:
math.round(2.5);
输出结果:
3
注意: 2.49 将舍入2 , 2.5 将舍入 3。很明显round()方法并不是我们想要的四舍五入处理方法。
以上就是js如何实现四舍五入的详细内容。