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 :-

Math.round(1.2345) // returns 1
Math.round(4.789) // returns 5

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

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

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

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

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

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);
  };
})();

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 :-

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

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

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 445 other subscribers

© 2011 Anuj Gakhar
%d bloggers like this: