Entry
How can I display a number with two decimals always?
How can I round a number to two decimals?
How can I round a number to n decimals?
Nov 16th, 2000 05:03
Thor Larholm, Martin Honnen,
If you always want to round to two decimals use a function alike
function round (n) {
n = Math.round(n * 100) / 100;
n = (n + 0.001) + '';
return n.substring(0, n.indexOf('.') + 3);
}
which converts your number into a string formatted as intented.
Examples:
alert(round(2))
alert(round(2.009))
Note that the result of the round function above is a string which is
what you usually need when you want to output data with js. Call
parseFloat on the result if you really need a number.
If you want round to a varying number of decimals use the function
function round (n, d) {
n = n - 0;
d = d || 2;
var f = Math.pow(10, d);
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);
}
which takes a number to round as the first argument and an optional
second argument defaulting to 2 which is the number of decimals you
want.
Examples:
alert(round(2.9, 0));
alert(round(2, 5));
alert(round(2.1245, 3));
Also note that starting with IE5.5 and NN6 there is a method
toFixed
for numbers which you could use instead of the above function e.g.
var n = 2;
alert(n.toFixed(2));
If you would like to have the same functionality in IE4/5 and Netscape
4.*/4.0*, this can be done by prototyping the Number object like this:
if (typeof(Number)!='undefined'&&typeof(Number.prototype)!='undefined'){
if (typeof(Number.prototype.toFixed)=='undefined'){
function Number_toFixed(d) {
var n = this;
d = d || 2;
var f = Math.pow(10, d);
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);
}
Number.prototype.toFixed = Number_toFixed;
}
}
Now you can use
toFixed
in IE 4/5 and Netscape 4.*/4.0* in the same manner as in IE 5.5 and NN6