Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript - how to round to nearest integer [duplicate]

Possible Duplicate:
How can I round of to whole numbers in JavaScript?

In javascript is there a function which allows me to round to the nearest integer? Either up or down.

So:

2.1 = 2
2.9 = 3
4.5 = 5
1.1 = 1

like image 821
Mazatec Avatar asked Aug 24 '11 08:08

Mazatec


People also ask

How do you round the number to the nearest integer in JavaScript?

round() The Math. round() function returns the value of a number rounded to the nearest integer.

How do you round doubles in JavaScript?

Using the Custom Function to Round a Number To2 Decimal Places in JavaScript. function roundToTwo(num) { return +(Math. round(num + "e+2") + "e-2"); } console. log(roundToTwo(2.005));

How do you round the number 7.25 to the nearest integer in JavaScript?

The Math. round() function in JavaScript is used to round the number passed as parameter to its nearest integer. Parameters : The number to be rounded to its nearest integer.


2 Answers

Use Math.round(number):

var i = Math.round(2.1);
like image 162
dacwe Avatar answered Oct 07 '22 18:10

dacwe


Math.round(x) and Math.floor(x)

both documented here

like image 28
NimChimpsky Avatar answered Oct 07 '22 18:10

NimChimpsky