JavaScript Reference ยท Math
Math.round() method
Reference for JavaScript Math.round(): round to the nearest integer, how halves and negatives behave, rounding to decimals and why 1.005 rounds oddly.
Math.round() returns the integer closest to a number. Math.round(4.4) is 4 and Math.round(4.6) is 5. When the fraction is exactly one half, JavaScript rounds up, toward positive infinity: Math.round(2.5) is 3, and Math.round(-2.5) is -2.
That "half goes up" rule is different from the "round half away from zero" taught in many schools, and from the banker's rounding used by some languages. Remember it when you work with negative numbers.
Math.round(4.6); // 5 Math.round(-2.5); // -2
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
Math.round(x)
| Name | Description |
|---|---|
x |
A number. Other values are converted to a number first. |
Return value: the integer nearest to x, with exact halves rounded toward positive infinity. NaN stays NaN; Infinity, -Infinity and -0 are returned unchanged. A value from -0.5 up to just below 0 gives -0.
Exceptions: a TypeError for a BigInt or a Symbol.
Usage notes
- Halves round toward positive infinity.
Math.round(-1.5)is-1, not-2. To round halves away from zero, useMath.sign(x) * Math.round(Math.abs(x)). - Rounding to decimals is approximate. The usual
Math.round(x * 100) / 100trick fails on values like1.005, which is stored slightly below1.005. See floating-point numbers for why. - For output, prefer formatting.
toFixed()andtoLocaleString()return strings suited to display, with consistent decimal places. - For money, use integers. Keep cents as whole numbers and round once, at the point where a fraction of a cent appears.
- Negative digits: the
roundTo(1234.5678, -2)example rounds to hundreds, because10 ** -2scales the other way. - Other directions:
Math.floor()rounds down,Math.ceil()rounds up, andMath.trunc()cuts toward zero. - Not for random integers.
Math.round(Math.random() * n)makes0andnhalf as likely as the other values; useMath.floorinstead.
Browser support
Math.round() is available in every browser and JavaScript runtime.
Related
Math.floor(),Math.ceil(),Math.trunc(),toFixed()- Lessons: Math, Numbers