By default, Javascript’s Math.round does not support decimal places.

If the fractional portion of number is .5 or greater, the argument is rounded to the next higher integer. If the fractional portion of number is less than .5, the argument is rounded to the next lower integer.

Here are 2 examples of the above :-

[js]
Math.round(1.2345) // returns 1
Math.round(4.789) // returns 5
[/js]

However, if you want to support decimal rounding in your code, you can use the following piece of code to do that.

[js]
function roundNumber(number, precision){
precision = Math.abs(parseInt(precision)) || 0;
var multiplier = Math.pow(10, precision);
return (Math.round(number * multiplier) / multiplier);
}
[/js]

This will let you round numbers to whatever precision you specify :-

[js]
roundNumber(1.2345, 2) // returns 1.23
roundNumber(4.789, 1) // returns 4.8
[/js]

However, you can certainly write this in a slightly better way. You can just hide this new implementation in a closure :-

[js]
Math.round = (function() {
var originalRound = Math.round;
return function(number, precision) {
precision = Math.abs(parseInt(precision)) || 0;
var multiplier = Math.pow(10, precision);
return (originalRound(number * multiplier) / multiplier);
};
})();[/js]

This will ensure your existing Math.round calls won’t need to be changed and will still work. Now, you can write the above custom function using native Math.round :-

[js]
Math.round(1.2345, 2) // returns 1.23
Math.round(4.789, 1) // returns 4.8
[/js]

You can do exactly the same thing with Math.ceil and Math.floor as well, if you want them to support decimal point calculations.

 

5 Responses to Rounding numbers with decimal places in Javascript

  1. Ernst Kuschke says:

    Roundnumber(8.575, 2)

  2. Ernst Kuschke says:

    This unfortunately doesn’t fix the JavaScript float error you encounter in this case.

  3. litepresence says:

    X = 0.9342987

    (Math.round(X*1000)/1000)

    debug ‘X: ‘ + X

    output

    X: 0.934

  4. Orif says:

    How the hell JAVA logo is doing in JavaScript?

Leave a Reply to Ernst Kuschke Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

© 2011 Anuj Gakhar
%d bloggers like this: