How to round to at most 2 decimal places, if necessary?(如有必要,如何舍入至多 2 位小数?)
问题描述
我希望最多舍入 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 位小数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!