Javascript round number
In this article, we will understand how to round a decimal to its nearest integer in javascript using its Math.round()
function with examples.
Javascript
Math
object has a round()
function which accepts a decimal number as argument and rounds it off to the nearest integer as per the following rules.
- If the first digit after decimal is greater than or equal to 5, then the number is rounded off to the next integer.
So, 6.5, 6.532, 6.683 etc., are rounded to 7. - If the first digit after decimal is lesser than 5, then the number is rounded off to the previous integer.
So, 6.4, 6.489, 6.199 etc., are rounded to 6. - Same rules apply for negative numbers except for the case when the first digit after decimal is exactly 0.5.
In this situation, the number is rounded off to the previous integer as opposed to next integer as for positive numbers.
So, -2.3, -5.4, -1.2 will be rounded off to -2, -5 and -1 respectively.
-2.6, -5.7, -1.8 will be rounded off to -3, -6 and -2 respectively, and
-8.5, -23.5, -45.5 will be rounded to -8, -23 and -45(Note this).
Syntax
round()
is a static method of Math
object and so, you don’t need create a javascript object to call it.
Following is the syntax of round()
function
Math.round(number)
where, number is the decimal value to be rounded.
Below are some of the examples of
Math.round()
let num1 = Math.round(89.5) console.log(num1); let num2 = Math.round(33.2) console.log(num2); let num3 = Math.round(21.2999) console.log(num3); console.log('--- Rounding negative numbers ---); let num4 = Math.round(-12.7) console.log(num4); let num5 = Math.round(-2.05) console.log(num5); // notice this let num6 = Math.round(-54.5) console.log(num6);
This is the output
90
33
21
— Rounding negative numbers —
-13
-2
-54
Passing string argument
round()
function may be provided a string as an argument. It will return the same result if the string is parseable or convertible to a number, such as ’34’, ‘67.4’ etc.
If the string is not convertible to numeric format, then round()
will return NaN
. Example,
console.log(Math.round('23.4')); console.log(Math.round('-12.5')); console.log(Math.round('one'));
Output will be
23
-12
NaN
Browser support
round()
function is supported by all the browsers. Following is a table of round()
compatibility with different browser versions.
Browser | Version |
---|---|
Chrome | 1 |
Firefox | 1 |
IE | 3 |
Edge | 12 |
Safari | 1 |
Opera | 3 |