如何在Javascript中舍入一个数字?
问题描述:
我想使用Javascript来舍入一个数字。由于这个数字是货币,我希望它像这些例子一样向上舍入(2个小数点):
I want to use Javascript to round up a number. Since the number is currency, I want it to round up like in these examples (2 decimal points):
- 192.168 => 192.20
- 192.11 => 192.20
- 192.21 => 192.30
- 192.26 => 192.30
- 192.20 => 192.20
- 192.168 => 192.20
- 192.11 => 192.20
- 192.21 => 192.30
- 192.26 => 192.30
- 192.20 => 192.20
如何使用Javascript实现这一目标?内置的Javascript函数将根据标准逻辑(小于和大于5)向上舍入数字。
How to achieve this using Javascript? The built-in Javascript function will round up the number based on standard logic (less and more than 5 to round up).
答
/**
* @param num The number to round
* @param precision The number of decimal places to preserve
*/
function roundUp(num, precision) {
precision = Math.pow(10, precision)
return Math.ceil(num * precision) / precision
}
roundUp(192.168, 1) //=> 192.2