Monday, May 5, 2008

Javascript Rounding

Just discovered:

Math.Round() function in Javascript return only the nearest whole number for any values.

So Math.Round(4.366) = 4
and Math.Round(8.33345) = 8.

We had a problem where we also needed to have the number rounded upto 2 or 3 decimal places.

Here is a way of doing the same:

function RoundNumber(Number, decimal)
{
var orgNumber = Math.round(Number*(Math.pow(10,decimal)));
var result = orgNumber /(Math.pow(10,decimal));
return result;
}


-- Ashutosh

No comments:

Post a Comment