The JavaScript Math.round() method
The Math.round() method rounds a number to the nearest integer; a value of exactly .5 rounds up. Math.round(4.5) is 5 and Math.round(4.4) is 4. To round to decimal places, scale first: Math.round(n * 100) / 100 rounds to two decimals.
Overview
Math.round() rounds to the nearest whole number, the way you learned in school: 4.5 and up go to 5, below 4.5 go to 4. The half-up rule is the one detail to remember, and note it applies to .5 exactly — 2.5 rounds to 3, and -2.5 rounds to -2 (toward positive infinity at the halfway point).
To round to a number of decimal places rather than to an integer, use the scale trick: multiply, round, divide back. Math.round(n * 100) / 100 keeps two decimals. This is great when you need a real rounded number to keep calculating with.
For displaying a fixed number of decimals — money, especially — toFixed() is usually the better choice, because it returns a string with the exact digits you asked for, including trailing zeros ("5.00"). Math.round() gives you a number; toFixed() gives you a formatted string. Pick based on whether you'll keep computing or just show the result.
Syntax
Math.round(4.5) // 5
Math.round(4.4) // 4
// round to 2 decimal places
Math.round(n * 100) / 100
Parameters
The Math.round() method accepts the following parameters.
| Parameter | Description |
|---|---|
x |
The number to round to the nearest integer. |
Example
<pre id="out" style="font:15px ui-monospace,monospace"></pre>
<script>
const price = 19.876;
const rounded = Math.round(price * 100) / 100;
document.getElementById('out').textContent =
'nearest int: ' + Math.round(price) + '\n' +
'2 decimals: ' + rounded; // nearest int: 20 / 2 decimals: 19.88
</script>
Best practices
- Round to decimals with the scale trick:
Math.round(n * 100) / 100for two places. - For display with fixed decimals (like money), prefer
toFixed(), which returns a formatted string. - Remember the halfway rule rounds up (toward positive infinity):
Math.round(2.5)is3. - Use Math.floor() or
Math.ceil()when you need to always go down or up.
Frequently asked questions
How does Math.round() handle .5?
Math.round(2.5) is 3 and Math.round(-2.5) is -2.How do I round to 2 decimal places in JavaScript?
Math.round(n * 100) / 100. For display, n.toFixed(2) returns a string.What is the difference between Math.round() and toFixed()?
Math.round() returns a number rounded to the nearest integer (or, with scaling, to decimals); toFixed() returns a string with a fixed number of decimal places, keeping trailing zeros.