JavaScript Math round() method - JavaScript Tutorial

JavaScript Math round() method

BLUF: This tutorial on JavaScript Math round() method provides an in-depth look at JavaScript's core features. It includes practical examples and code snippets to help you master modern JS development.
Key Discovery: JavaScript Math round() method

Understanding JavaScript Math round() method is crucial for building dynamic, interactive web applications. Explore the examples below to see it in action.

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:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience