如何在Javascript中舍入一个数字? [英] How to round up a number in Javascript?
本文介绍了如何在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
这篇关于如何在Javascript中舍入一个数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文