JavaScript provides the Math.round() function in order to round a given number which is generally a float or double into the nearest integer. The Math.round() function is supported by all major browsers completely.
Math.round() Function Syntax
Math.round() function has a very simple syntax where the value or variable provided to the function and the rounded value is returned as a result.
Math.round(val)
- val is a value or variable which will be rounded to the upper or lower integer value.
Math.round() Function Examples
Below you can find different examples about the Math.round() function.
Math.round(1);
// 1
Math.round(0);
// 0
Math.round(1.1);
// 1
Math.round(0.1);
// 0
Math.round(1.5);
// 2
Math.round(2.4);
// 2
Math.round(2.6);
// 3
Math.round(-0.4);
// -0
Math.round(-0.5);
// -0
Math.round(-0.6);
// -1
Math.round(-3.6);
// -4
Math.round("2.4");
// 2
Math.round("2.6");
// 3
Math.round("-0.4");
// -0
Math.round("-0.5");
// -0
Math.round("-0.6");
// -1
We can see that Math.round(-0.5); is resulted in -0 which is a bit strange but there is no problem. As 0 is not a positive or negative number preceding 0 with + or – are the same thing. You can also see that strings can be rounded if their characters converted into numbers.
Math.round() Function For Negative Values
Rounding positive numbers and understanding the rounding operating about positive numbers are very easy to understand. But negative numbers can be a bit confusing. Actually it is very clear that negative numbers will be rounded to the higher values. For example, -2 is bigger than -3, and values like -2.5, -2.3 will be rounded into the -2 where values like -2.6 or -2.8 will be rounded into the -3.
Math.round(-0.4);
// -0
Math.round(-0.5);
// -0
Math.round(-0.6);
// -1
Math.round(-3.6);
// -4
Math.round() Function Errors
While using the Math.round() function there may be some errors and exceptions. Below you can find some error and exception cases about rounding operation.
- Non-numeric string round operation will result NaN .
- Array more than one integer will result the NaN value as there are multiple input and can not return single result.
- Empty variable will result NaN becuase there is no value to round.
- Empty string will result NaN as there is no number to round.