Reputation: 11035
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()
Upvotes: 2
Views: 4119
Reputation: 36
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;
}
Upvotes: 0
Reputation: 14434
The Math.ceil(x) function returns the smallest integer greater than or equal to a number "x".
var rounded = Math.ceil(yourNumber * 100)/100;
Upvotes: 8