AppDividend
Latest Code Tutorials

JavaScript Math.round Method: The Complete Guide

Rounding a number in mathematics involves replacing a number with an approximation of a number that results in a shorter, more straightforward, or more explicit representation of said number based on specific rounding definitions.

JavaScript Math.round

Javascript Math.round() is a built-in function that returns the value of a number rounded to the nearest integer. The Math.round() method rounds the number to the nearest integer.

If the fractional portion of an argument is more than 0.5, the argument is turned to an integer with the next higher absolute value. If it is less than 0.5, then the argument is rounded to the integer with the lower value. Finally, if the fractional portion is exactly 0.5, the argument is rounded to the next integer in the direction of +∞.

Syntax

Math.round(x)

Parameters

Where is a number, the value of a given number is rounded to the nearest integer.

Let’s see the following example.

// app.js

console.log(Math.round(21.19));
console.log(Math.round(19.21));
console.log(Math.round(46.21));
console.log(Math.round(21.52));

OutputJavascript Math Round Example | Math.round() Tutorial

The Math.round() function returns a value of the number rounded to the nearest integer.

If we want to round off a number to its nearest integer, the Math.round() function should be implemented.

The Math.round() function itself rounds off a negative number when passed as the parameter. See the following example.

// app.js

console.log(Math.round(-21.52));

OutputMath.round() Tutorial

Javascript Math.round to 2 decimal places

To round 2 decimal places in JavaScript, use the Math.round() function. The Math.round() function returns the value of a number rounded to the nearest integer.

// app.js

let num = 21.39999

let rnd = Math.round(num * 100) / 100
console.log(rnd)

Output

21.4

Javascript Math.round to 1 decimal place

To round 1 decimal place in JavaScript, use the math.round() function.

// app.js

let num = 21.111111

let rnd = Math.round(num * 10) / 10
console.log(rnd)

Output

21.1

That’s it for this tutorial.

Related posts

JavaScript Math.pow()

JavaScript Math.min()

JavaScript Math.random()

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.