我有一堆数字,例如797.3333333333334
,852.22222111
,933.111023
,我想要总结到最近的便士,这样我已经提到过的数字分别是797.34
,852.23
,933.12
。
我说最近的便士,但你也可以把它称为最近的十分之一。
有一个天花板功能,但只有圆形到最接近的整数,Math.round()
也是如此
The Math.ceil(x) function returns the smallest integer greater than or equal to a number "x".
var rounded = Math.ceil(yourNumber * 100)/100;
就这样做:Math.ceil(number * 100) / 100
。
正确舍入到最近的便士:
var yourNumber = 5.495;
yourNumber = Math.round(yourNumber * 100)/100;
alert(yourNumber);
总是四舍五入到最近的便士:
function precision(a) {
if (!isFinite(a)) return 0;
var e = 1, p = 0;
while (Math.round(a * e) / e !== a) {
e *= 10; p++;
}
return p;
}
if (precision(yourNumber) >= 3) {
yourNumber = (Math.trunc(yourNumber * 100)/100) * 1 + 0.01;
}