How can I round to whole numbers in JavaScript?

105,142

Solution 1

Use the Math.round() function to round the result to the nearest integer.

Solution 2

//method 1
Math.ceil(); // rounds up
Math.floor(); // rounds down
Math.round(); // does method 2 in 1 call

//method 2
var number = 1.5; //float
var a = parseInt(number); // to int
number -= a; // get numbers on right of decimal

if(number < 0.5) // if less than round down
    round_down();
else // round up if more than
    round_up();

either one or a combination will solve your question

Solution 3

total = Math.round(total);

Should do it.

Solution 4

Use Math.round to round the number to the nearest integer:

total = Math.round(x/15*100);

Solution 5

a very succinct solution for rounding a float x:

x = 0|x+0.5

or if you just want to floor your float

x = 0|x

this is a bitwise or with int 0, which drops all the values after the decimal

Share:
105,142

Related videos on Youtube

idontknowhow
Author by

idontknowhow

Updated on August 05, 2020

Comments

  • idontknowhow
    idontknowhow over 3 years

    I have the following code to calculate a certain percentage:

    var x = 6.5;
    var total;
    
    total = x/15*100;
    
    // Result  43.3333333333
    

    What I want to have as a result is the exact number 43 and if the total is 43.5 it should be rounded to 44

    Is there way to do this in JavaScript?

  • Afzaal Ahmad Zeeshan
    Afzaal Ahmad Zeeshan over 10 years
    helped me too! :) Thanks for the MDN link buddy :)
  • hmakholm left over Monica
    hmakholm left over Monica over 10 years
    The credit for the link goes to @Jeremy. Thanks for inserting it -- it made starting out on SO a lot more fun to have the fifth answer I ever wrote get as many votes as this one did, which was surely due to the link. :-)
  • dot-punto-dot
    dot-punto-dot almost 7 years
    Didn't OP want to round UP? If so maybe Math.ceil() would be more appropriate
  • hmakholm left over Monica
    hmakholm left over Monica almost 7 years
    @martellalex: From the question, the OP wanted 43.333 to round to 43 but 43.5 to round to 44, which exactly matches ECMAScript's Math.round()'s behavior of rounding to nearest, and running exact half-integers towards positive infinity.