How can I round to an integer in JavaScript?

I have the following code to calculate a certain percentage:

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

As a result, I want to get the exact number 43 , and if the sum is 43.5 , it should be rounded to 44

Is there any way to do this in JavaScript?

+72
javascript operators rounding
Aug 6 2018-11-11T00:
source share
5 answers

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

+136
Aug 6 '11 at 16:10
source share
 //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(); 

any or combination will solve your question

+48
Aug 6 '11 at 16:10
source share
 total = Math.round(total); 

Must do it.

+8
Aug 6 '11 at 16:13
source share

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

 total = Math.round(x/15*100); 
+6
Aug 6 '11 at 16:10
source share

very concise solution for rounding float x:

x = 0|x+0.5

or if you just want to put your float

x = 0|x

is it bitwise or with int 0 that discards all values ​​after decimal

+3
Aug 04 '16 at 18:12
source share



All Articles