JavaScript Math round Method is used to round a given number to the nearest integer. It takes a single argument, which is the number to be rounded.
Math.round(num)
To round a number to a specific number of decimal places, you can use the following syntax:
Math.round(num * 10**decimalPlaces) / 10**decimalPlaces
JavaScript Math round Method example
Simple example code.
<!DOCTYPE html>
<html>
<body>
<script>
let num = 2.5;
let rounded = Math.round(num);
console.log(rounded);
console.log(typeof(rounded))
</script>
</body>
</html>
Output:
Using Math.round()
method to round to a specified number of decimal places. You can multiply the number by a factor of 10 raise to the power of the number of decimal places you want and divide the result by the same factor.
let num = 2.546;
let rounded = Math.round(num * 100) / 100;
console.log(rounded); // Output: 2.55
The Math.round()
method returns the rounded value of the input number as an integer.
Math.round() behavior | Example | Output |
---|---|---|
If the fractional portion > 0.5 | Math.round(2.6) | 3 |
Math.round(3.7) | 4 | |
If the fractional portion < 0.5 | Math.round(2.4) | 2 |
Math.round(3.2) | 3 | |
If the fractional portion = 0.5 | Math.round(2.5) | 3 |
Math.round(3.5) | 4 | |
Math.round(4.5) | 5 |
Do comment if you have any doubts or suggestions on this Js math topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version