Javascript Round Number function
function round_number(n, d) {
n = n - 0;
if (d == null) d = 2;
var f = Math.pow(10, d);
n += Math.pow(10, - (d + 1));
n = Math.round(n * f) / f;
n += Math.pow(10, - (d + 1));
n += '';
return d == 0 ? n.substring(0, n.indexOf('.')) : n.substring(0, n.indexOf('.') + d + 1);
}
Example:
price = round_number(4174.315); alert(price); //Result: 4174.32


28. Feb, 2008












why not use the toFixed method? It also rounds the result i.e.
var number = 3.14567
alert(number.toFixed(2));
==> 3.15
that is a nice idea also. thanks for the tip brian.
Actualy there are many cases when we do not want pure math round for prices, as
(e.g. $4.021 => $4.05)
1st: prices should be always rounded up
2nd: usually round to 5 cents (unless you have those stuppid 9.99 prices)
So, we get wierd price like $4.3126 after some calculation (item price + some delivery + WAT * % discount bla-bla-bla) and need to get nice-looking price like $4.35
function roundPrice(price)
{
var priceMultiplied = Math.ceil(price*100);
var reminder = priceMultiplied % 5;
var compliment = reminder?5-reminder:0;
var priceRounded = (priceMultiplied + compliment)/100;
return priceRounded.toFixed(2);
}
test cases:
roundPrice(18.32) = 18.35
roundPrice(20.01) = 20.05
roundPrice(21.39) = 21.40
roundPrice(29.95) = 29.95
roundPrice(29.96) = 30.00
roundPrice(29.951) = 30.00