本文介绍了如有必要,如何舍入至小数点后2位?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想四舍五入至小数点后两位,但仅在必要时四舍五入.
I'd like to round at most 2 decimal places, but only if necessary.
输入:
10
1.7777777
9.1
输出:
10
1.78
9.1
如何在JavaScript中执行此操作?
How can I do this in JavaScript?
推荐答案
使用 Math.round():
Math.round(num * 100) / 100
或者更具体地讲,以确保1.005之类的信息正确取整,请使用 Number.EPSILON :
Or to be more specific and to ensure things like 1.005 round correctly, use Number.EPSILON :
Math.round((num + Number.EPSILON) * 100) / 100
这篇关于如有必要,如何舍入至小数点后2位?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!