How do I round a number in JavaScript?

If you need to round to a certain number of digits use the following function

function roundNumber(number, digits) {
            var multiple = Math.pow(10, digits);
            var rndedNum = Math.round(number * multiple) / multiple;
            return rndedNum;
        }

You hav to convert your input into a number and then round them:

function toInteger(number){ 
  return Math.round(  // round to nearest integer
    Number(number)    // type cast your input
  ); 
};

Or as a one liner:

function toInt(n){ return Math.round(Number(n)); };

Testing with different values:

toInteger(2.5);           // 3
toInteger(1000);          // 1000
toInteger("12345.12345"); // 12345
toInteger("2.20011E+17"); // 220011000000000000

According to the ECMAScript specification, numbers in JavaScript are represented only by the double-precision 64-bit format IEEE 754. Hence there is not really an integer type in JavaScript.

Regarding the rounding of these numbers, there are a number of ways you can achieve this. The Math object gives us three rounding methods wich we can use:

The Math.round() is most commonly used, it returns the value rounded to the nearest integer. Then there is the Math.floor() wich returns the largest integer less than or equal to a number. Lastly we have the Math.ceil() function that returns the smallest integer greater than or equal to a number.

There is also the toFixed() that returns a string representing the number using fixed-point notation.

Ps.: There is no 2nd argument in the Math.round() method. The toFixed() is not IE specific, its within the ECMAScript specification aswell


Here is a way to be able to use Math.round() with a second argument (number of decimals for rounding):

// 'improve' Math.round() to support a second argument
var _round = Math.round;
Math.round = function(number, decimals /* optional, default 0 */)
{
  if (arguments.length == 1)
    return _round(number);

  var multiplier = Math.pow(10, decimals);
  return _round(number * multiplier) / multiplier;
}

// examples
Math.round('123.4567', 2); // => 123.46
Math.round('123.4567');    // => 123

You can also use toFixed(x) or toPrecision(x) where x is the number of digits.

Both these methods are supported in all major browsers