How do I round a number in JavaScript?

93,342

Solution 1

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

Solution 2

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

Solution 3

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

Solution 4

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

Solution 5

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

Share:
93,342
Ace
Author by

Ace

Updated on July 04, 2020

Comments

  • Ace
    Ace almost 4 years

    While working on a project, I came across a JS-script created by a former employee that basically creates a report in the form of

    Name : Value
    Name2 : Value2
    

    etc.

    The peoblem is that the values can sometimes be floats (with different precision), integers, or even in the form 2.20011E+17. What I want to output are pure integers. I don't know a lot of JavaScript, though. How would I go about writing a method that takes these sometimes-floats and makes them integers?

  • Ace
    Ace over 15 years
    So Math.round(532.24,0) = 532?
  • Rhys
    Rhys over 15 years
    Good explanation and my bad for supplying the second arguement; I'll edit my answer to reflect this.
  • Rhys
    Rhys over 15 years
    Math.round() does not have a second argument, as it rounds the number to the nearest integer.
  • a1ashiish
    a1ashiish over 15 years
    You just have to go for the spec =]
  • Ruan Mendes
    Ruan Mendes over 12 years
    The one liner is exactly the same as the 4 liner :)
  • AaronAsAChimp
    AaronAsAChimp over 11 years
    The actual one-liner is 'Math.round(number)'. The whole type casting business is unnecessary. In JavaScript strings are automatically coerced to numbers when needed.
  • matewka
    matewka over 11 years
    @AaronAsAChimp I can't agree - if the string includes other characters than digits and . or E+ then Math.round will return NaN.
  • AaronAsAChimp
    AaronAsAChimp over 11 years
    On the contrary, the Number function uses the same algorithm for converting numbers as coercion. The algorithm (Defined in Section 9.3.1 of ECMA-262 3rd edition) handles a wide variety of formats. Basically anything that would be a valid number, including decimals, exponent notation, and hexadecimal. (seriously '0xFF' == 255)
  • Denilson Sá Maia
    Denilson Sá Maia over 10 years
    It might be better to use .toFixed(), added in JavaScript 1.5.
  • Bernhard Barker
    Bernhard Barker almost 10 years
    Floor != round. floor(19.5) == 19, but round(19.5) = 20.
  • Chris
    Chris over 8 years
    Note that toFixed() outputs a string. (0.1 + 0.2).toFixed(2) yields the string "0.30". But you can get it back into a number by prepending "+". +(0.1 + 0.2).toFixed(2) yields the number 0.3
  • qwertz
    qwertz over 6 years
    if you are using lodash u can lodash's round function: _.round(number, precision)
  • greenskin
    greenskin over 6 years
    Actually I think that what @qwertz suggests is the best answer you can get on SO.