Math.round() function with examples.
Mathobject 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).
round() is a static method of
Following is the syntax of
where, number is the decimal value to be rounded.
Below are some of the examples of
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
— Rounding negative numbers —
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
console.log(Math.round('23.4')); console.log(Math.round('-12.5')); console.log(Math.round('one'));
Output will be
round() function is supported by all the browsers. Following is a table of
round() compatibility with different browser versions.