JavaScript: Math round() function
This JavaScript tutorial explains how to use the math function called round() with syntax and examples.
Description
In JavaScript, round() is a function that is used to return a number rounded to the nearest integer value. Because the round() function is a static function of the Math object, it must be invoked through the placeholder object called Math.
Syntax
In JavaScript, the syntax for the round() function is:
Math.round(number);
Parameters or Arguments
- number
- The number that will be rounded.
Returns
The round() function returns a number rounded to the nearest integer. In other words, the number is rounded to 0 decimal places.
If the number is a negative value, the round() function rounds up towards zero which is different behavior than the round function in other languages.
Note
- Math is a placeholder object that contains mathematical functions and constants of which round() is one of these functions.
Example
Let's take a look at an example of how to use the round() function in JavaScript.
For example:
console.log(Math.round(32.65));
console.log(Math.round(8.1));
console.log(Math.round(-4.2));
In this example, we have invoked the round() function using the Math class.
We have written the output of the round() function to the web browser console log, for demonstration purposes, to show what the round() function returns.
The following will be output to the web browser console log:
33 8 -4
In this example, the first output to the console log returned 33 which is 32.65 rounded to the nearest integer.
The second output to the console log returned 8 which is 8.1 rounded to the nearest integer.
The third output to the console log returned -4 which is -4.2 rounded to the nearest integer. Notice that when dealing with negative numbers, the round() function rounds up towards zero and in this case, returned -4 and not -5. This behavior is different than the round functions in other languages.
Advertisements