0
0
JavascriptHow-ToBeginner · 3 min read

How to Use Math.round in JavaScript: Syntax and Examples

Use Math.round(number) in JavaScript to round a decimal number to the nearest whole number. It returns the closest integer, rounding halves away from zero (e.g., 2.5 becomes 3).
📐

Syntax

The Math.round() function takes one argument, a number, and returns the nearest integer.

  • number: The decimal number you want to round.
javascript
Math.round(number)
💻

Example

This example shows how Math.round() rounds different decimal numbers to the nearest integer.

javascript
console.log(Math.round(4.7));  // Output: 5
console.log(Math.round(4.4));  // Output: 4
console.log(Math.round(2.5));  // Output: 3
console.log(Math.round(-1.5)); // Output: -1
Output
5 4 3 -1
⚠️

Common Pitfalls

One common mistake is expecting Math.round() to always round down or up. It rounds to the nearest integer, rounding halves away from zero.

Also, it only rounds to whole numbers, so to round to decimals you must multiply and divide.

javascript
const num = 2.345;
// Wrong: expecting rounding to 2.3
console.log(Math.round(num)); // Outputs 2

// Correct: round to 1 decimal place
const rounded = Math.round(num * 10) / 10;
console.log(rounded); // Outputs 2.3
Output
2 2.3
📊

Quick Reference

UsageDescription
Math.round(4.7)Returns 5, rounds up from .7
Math.round(4.4)Returns 4, rounds down from .4
Math.round(2.5)Returns 3, rounds .5 up
Math.round(-1.5)Returns -1, rounds .5 up (away from zero)
Math.round(num * 10) / 10Rounds to 1 decimal place

Key Takeaways

Math.round(number) rounds a decimal to the nearest whole number.
It rounds halves (.5) up away from zero to the next integer.
To round to decimals, multiply, round, then divide.
Math.round() only works with numbers, not strings.
Use Math.round() for simple rounding needs in JavaScript.