JavaScript Math.round() Method



The JavaScript Math.round() method accepts a numeric value as a parameter, round it to the nearest integer and returns the result.

The Math.round() method works as follows −

  • If the fractional portion of the number is less than 0.5, Math.round() returns the greatest integer less than or equal to x.
  • If the fractional portion of the number is 0.5 or greater, Math.round() returns the smallest integer greater than or equal to x.

Syntax

Following is the syntax of JavaScript Math.round() method −

Math.round(x);

Parameters

This method accepts only one parameter. The same is described below −

x: The number to be rounded.

Return value

This method returns the nearest integer to the given number. If the fractional part is .5 or greater, the number is rounded UP. Otherwise, it is rounded DOWN.

Example 1

In the following example, we are demonstrating the basic usage of JavaScript Math.round() method −






Output

If we execute the above program, the specified positive integers got rounded to the nearest integers.

Example 2

Here, we are passing negative arguments to the Math.round() method −






Output

If we execute the program, it returns "-5", "-5", and "-6" as result.

Example 3

If we pass "null" as an argument to this method, it returns "0" as result −






Output

As we can see in the output, it returned "null".

Example 4

If we provide a non-numeric or empty number as an argument to this method, it returns "NaN" as result −






Output

As we can see in the output, it returned "NaN".

Advertisements