JavaScript Math.round()
Syntax & Examples
Math.round() static-method
The Math.round() method in JavaScript returns the value of a number rounded to the nearest integer. If the fractional part of the number is 0.5 or greater, the argument is rounded to the next higher integer; if the fractional part is less than 0.5, the argument is rounded to the lower integer. It is a static method of Math, meaning it is always used as Math.round() and not as a method of a Math object created (Math is not a constructor).
Syntax of Math.round()
The syntax of Math.round() static-method is:
Math.round(x)
This round() static-method of Math returns the value of the number x rounded to the nearest integer.
Parameters
Parameter | Optional/Required | Description |
---|---|---|
x | required | A number to be rounded to the nearest integer. |
Return Type
Math.round() returns value of type Number
.
✐ Examples
1 Using Math.round() with a positive number
In this example, we use the Math.round()
method to round the number 4.7 to the nearest integer.
For example,
- We call
Math.round()
with 4.7 as the argument. - The method returns the value of 4.7 rounded to the nearest integer.
- We log the result to the console using
console.log()
.
JavaScript Program
console.log(Math.round(4.7));
Output
5
2 Using Math.round() with a negative number
In this example, we use the Math.round()
method to round the number -4.7 to the nearest integer.
For example,
- We call
Math.round()
with -4.7 as the argument. - The method returns the value of -4.7 rounded to the nearest integer.
- We log the result to the console using
console.log()
.
JavaScript Program
console.log(Math.round(-4.7));
Output
-5
3 Using Math.round() with a number having .5 fractional part
In this example, we use the Math.round()
method to round the number 5.5 to the nearest integer.
For example,
- We call
Math.round()
with 5.5 as the argument. - The method returns the value of 5.5 rounded to the nearest integer.
- We log the result to the console using
console.log()
.
JavaScript Program
console.log(Math.round(5.5));
Output
6
Summary
In this JavaScript tutorial, we learned about round() static-method of Math: the syntax and few working examples with output and detailed explanation for each example.