JavaScriptNumbers and Math
Math. round()
Rounds a number to the nearest integer.
- Returns
- The nearest integer.
Example
#JavaScript
console.log(Math.round(4.4))
console.log(Math.round(4.5))
console.log(Math.round(-2.5))
console.log(Math.round(81.666 * 10) / 10)Console
4
5
-2
81.7
Definition and usage
#The Math.round() function rounds a number to the nearest integer. A fraction of 0.5 or more rounds up, less than that rounds down.
Watch out with negative numbers: at exactly half, rounding goes toward positive infinity, so Math.round(-2.5) gives -2, not -3.
To round to a number of decimal places, use multiplication: Math.round(x * 100) / 100. Keep in mind, though, that floating-point numbers aren’t always exact.
Syntax
#Syntax
Math.round(x)Parameters
#x
number
The number to round.
Browser support
#Widely available
Works in all modern browsers, phones included. You can use it without worry.
- Chrome
- Edge
- Firefox
- Safari
Good practices
#- For displaying a number with decimal places,
toFixed()orIntl.NumberFormatare more convenient. - Remember the trio:
roundto the nearest,floordown,ceilup.
Related entries
#- Math.floor()Rounds a number down, to the nearest smaller integer.
- Math.ceil()Rounds a number up, to the nearest larger integer.
- Math.trunc()Cuts off the fractional part of a number, leaving the integer part.
- Number.prototype.toFixed()Converts a number into a string with a given number of decimal places.
Spotted a mistake or missing an example? Write to us.