Math.round()
ES1+Returns the value of a number rounded to the nearest integer.
Syntax
Math.round(x)Parameters
x number A number
Return Value
The value of the number rounded to the nearest integer
Examples
console.log(Math.round(4.5));
console.log(Math.round(4.4));
console.log(Math.round(-4.5)); 📌 When to Use
Use Math.round() for standard rounding in user-facing displays, statistics, and when you need the mathematically nearest integer value.
⚠️ Common Mistakes
Not understanding that Math.round(-4.5) returns -4, not -5 (rounds toward positive infinity at .5).
Using Math.round() for financial calculations where bankers rounding or fixed decimal places are required.
✅ Best Practices
For rounding to decimal places, multiply, round, then divide: Math.round(num * 100) / 100 for 2 decimals.
For financial applications, consider using libraries like decimal.js or big.js for precise rounding.
⚡ Performance Notes
Math.round() performs a single CPU operation. When rounding many numbers, the multiply-round-divide pattern for decimal places adds minimal overhead.
🌍 Real World Example
Product Rating Display
Round product ratings to show user-friendly star ratings on e-commerce sites.
function displayRating(rawRating) {
const roundedRating = Math.round(rawRating * 2) / 2; // Round to nearest 0.5
const fullStars = Math.floor(roundedRating);
const hasHalfStar = roundedRating % 1 !== 0;
return {
display: roundedRating.toFixed(1),
fullStars,
hasHalfStar,
emptyStars: 5 - fullStars - (hasHalfStar ? 1 : 0)
};
}
console.log(displayRating(4.3)); // { display: '4.5', fullStars: 4, hasHalfStar: true, emptyStars: 0 }
console.log(displayRating(3.7)); // { display: '3.5', fullStars: 3, hasHalfStar: true, emptyStars: 1 }