I have a bunch of numbers, for example 797.3333333333334
, 852.22222111
, 933.111023
, which I want to ALWAYS round up to the nearest penny, such that the numbers I already mentioned would be 797.34
, 852.23
, 933.12
, respectively.
I said the nearest penny, but you might also call it the nearest tenth.
There is a ceiling function, but that only rounds to the nearest integer, as does Math.round()
I have a bunch of numbers, for example 797.3333333333334
, 852.22222111
, 933.111023
, which I want to ALWAYS round up to the nearest penny, such that the numbers I already mentioned would be 797.34
, 852.23
, 933.12
, respectively.
I said the nearest penny, but you might also call it the nearest tenth.
There is a ceiling function, but that only rounds to the nearest integer, as does Math.round()
-
ceil
doesn't round to nearest integer, it gets the first integer larger or equal to your number. – XCS Commented Nov 22, 2014 at 22:28
3 Answers
Reset to default 8The Math.ceil(x) function returns the smallest integer greater than or equal to a number "x".
var rounded = Math.ceil(yourNumber * 100)/100;
Just do it like this: Math.ceil(number * 100) / 100
.
Properly rounding to the nearest penny:
var yourNumber = 5.495;
yourNumber = Math.round(yourNumber * 100)/100;
alert(yourNumber);
Always round up to the nearest penny:
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;
}