JavaScript round float to n decimal points
The best you can do with built in JavaScript functions is to round a number to the nearest integer using the method Math.round(x), so to round a float to n decimal points we need to come up with our own function.
The function round_float() rounds a floating point number x to n decimals, if you ommit the parameter n, the function will have the same behaviour as the round() method, here is the round_float function definition:
1 2 3 4 5 6 7 | function round_float(x,n){ if(!parseInt(n)) var n=0; if(!parseFloat(x)) return false; return Math.round(x*Math.pow(10,n))/Math.pow(10,n); } |
With prototyping
Dmitry suggested a better approach using prototyping:
1 2 3 4 5 6 7 8 9 10 | if (!Number.toFixed) { Number.prototype.toFixed=function(n){ return Math.round(this*Math.pow(10, n)) / Math.pow(10, n); } } // example: floating_number = 123.45687; decimal_points = 2; window.alert(floating_number.toFixed(decimal_points)); |
It would be better to use prototyping here. Newer browsers support toFixed() function. Older don’t.
So here’s the way to do it:
if (!Number.toFixed) {
Number.prototype.toFixed=function(x) {
var temp=this;
temp=Math.round(temp*Math.pow(10,x))/Math.pow(10,x);
return temp;
}}
example:
f=123.23453
window.alert(f.toFixed(2));
make it simpler
function round(val, prec)
{
return parseFloat(parseFloat(val).toFixed(prec));
}
This is very clean, if val is not a number the function will return NaN (Not a Number)
Thanks Chat!