JavaScript Math.round() Method
-
Syntax of
Math.round() -
Example 1: Use the
Math.round()Method in JavaScript -
Example 2: Use the
Math.round()Method With Non-Numeric Values
The Math.round() method rounds a number to the closest integer value. If the given fractional number is less than .50, this method will round up the number with the lower integer absolute value.
On the other hand, if the fractional number is greater than or equal to .50, this method will round up the number with the next higher integer absolute value.
Syntax of Math.round()
Math.round(num)
Parameters
num - The parameter num refers to a required numeric value.
Return
The Math.round() method returns the closest absolute integer value from a given number.
Example 1: Use the Math.round() Method in JavaScript
const result1 = Math.round(3.69)
const result2 = Math.round(4.50)
const result3 = Math.round(7.33)
const result4 = Math.round(-4.50)
const result5 = Math.round(-4.51)
const result6 = Math.round(99)
console.log(result1)
console.log(result2)
console.log(result3)
console.log(result4)
console.log(result5)
console.log(result6)
Output:
4
5
7
-4
-5
99
The fraction number for the first two cases equals and exceeds .50. As a result, this method rounded up those numbers from 3 to 4 and 4 to 5.
For the third case, the fraction number is lower than .50, and this method rounded up the number with the lower integer absolute value.
Example 2: Use the Math.round() Method With Non-Numeric Values
const result1 = Math.round('A')
const result2 = Math.round()
console.log(result1)
console.log(result2)
Output:
NaN
NaN
This method returns NaN for both cases. The reason is the parameters are not a number.
Niaz is a professional full-stack developer as well as a thinker, problem-solver, and writer. He loves to share his experience with his writings.
LinkedIn