cyb*_*fly 156 javascript rounding
我想使用Javascript来舍入一个数字.由于这个数字是货币,我希望它像这些例子一样向上舍入(2个小数点):
如何使用Javascript实现这一目标?内置的Javascript函数将根据标准逻辑(小于和大于5)向上舍入数字.
And*_*all 298
/**
* @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
Run Code Online (Sandbox Code Playgroud)
sur*_*ran 26
稍晚但是,可以为此创建一个可重用的javascript函数:
// Arguments: number to round, number of decimal places
function roundNumber(rnum, rlength) {
var newnumber = Math.round(rnum * Math.pow(10, rlength)) / Math.pow(10, rlength);
return newnumber;
}
Run Code Online (Sandbox Code Playgroud)
将该功能称为
alert(roundNumber(192.168,2));
Run Code Online (Sandbox Code Playgroud)
Sha*_*had 20
正常舍入将适用于小调整:
Math.round(price * 10)/10
Run Code Online (Sandbox Code Playgroud)
如果要保留货币格式,可以使用Number方法 .toFixed()
(Math.round(price * 10)/10).toFixed(2)
Run Code Online (Sandbox Code Playgroud)
虽然这会使它成为一个String =)
非常接近TheEye的答案,但我改变了一点让它工作:
var num = 192.16;
console.log( Math.ceil(num * 10) / 10 );
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
171005 次 |
最近记录: |