JavaScript Math round() method

The round method in JavaScript is utilized to round a specified number to the nearest integer and subsequently returns this value. In cases where the provided number is already an integer, the round method will simply return it as is.

Syntax

The syntax for the round function is outlined as follows:

Example

Math.round(num)

Parameter

num - A number.

Return

The closest integer value of the given number.

JavaScript Math round method example

In this section, we will explore the round method by examining a variety of examples.

Example 1

Let’s examine an instance that demonstrates how to elevate a specified number to the nearest integer value.

Example

<script>

document.writeln(Math.round(7.2)+"<br>");

document.writeln(Math.round(0.6));

</script>

Output:

Example 2

In this instance, we will demonstrate the utilization of the round function with negative integers.

Example

<script>

document.writeln(Math.round(-7.2)+ "<br>");

document.writeln(Math.round(-0.6));

</script>

Output:

Output

-7

-1

Example 3

In this section, you have the opportunity to experiment with the round function by creating your own test cases.

Example

<script>

function display()

{

  var x=document.getElementById("num").value;

document.getElementById("result").innerHTML=Math.round(x);

}

</script>

<form>

  Enter a number: <input type="text" id="num">

  <input type="button"  onclick="display()" value="submit">

  </form>

  <p><span id="result"></span></p>

Input Required

This code uses input(). Please provide values below: