JavaScript Math round()

The JavaScript Math.round() function returns the number rounded to the nearest integer.

The syntax of the Math.round() function is:

Math.round(x)

round(), being a static method, is called using the Math class name.


Math.round() Parameters

The Math.round() function takes in:

  • x - A number

Return value from Math.round()

Math.round() returns the value of the number rounded to the nearest integer as follows:

  • If the fractional portion > 0.5, x is rounded to integer with higher absolute value.
  • If the fractional portion < 0.5, x is rounded to integer with lower absolute value.
  • If the fractional portion = 0.5, x is rounded to the next integer in the direction of +∞.

Example: Using Math.round()

// using Math.round()
var num = Math.round(1.8645);
console.log(num); // 2

var num = Math.round(10.49);
console.log(num); // 10

var num = Math.round(4.5);
console.log(num); // 5

var num = Math.round(-4.5);
console.log(num); // -4

// Returns 0 for null
var num = Math.round(null);
console.log(num); // 0

// Returns NaN for non-numeric types
var num = Math.round("JavaScript");
console.log(num); // NaN

Output

2
10
5
-4
0
NaN

Note: Math.round() returns 0 for null rather than NaN.


Recommended readings: