How to Round Numbers in JavaScript: Simple Guide
In JavaScript, you can round numbers using
Math.round() to round to the nearest integer, Math.floor() to round down, and Math.ceil() to round up. These built-in functions help you control how numbers are rounded in your code.Syntax
JavaScript provides three main functions to round numbers:
Math.round(number): Rounds to the nearest integer.Math.floor(number): Rounds down to the nearest integer.Math.ceil(number): Rounds up to the nearest integer.
Each function takes a single number as input and returns an integer.
javascript
Math.round(number) Math.floor(number) Math.ceil(number)
Example
This example shows how to use each rounding function on the number 4.7 and 4.3.
javascript
const num1 = 4.7; const num2 = 4.3; console.log('Math.round(4.7):', Math.round(num1)); console.log('Math.floor(4.7):', Math.floor(num1)); console.log('Math.ceil(4.7):', Math.ceil(num1)); console.log('Math.round(4.3):', Math.round(num2)); console.log('Math.floor(4.3):', Math.floor(num2)); console.log('Math.ceil(4.3):', Math.ceil(num2));
Output
Math.round(4.7): 5
Math.floor(4.7): 4
Math.ceil(4.7): 5
Math.round(4.3): 4
Math.floor(4.3): 4
Math.ceil(4.3): 5
Common Pitfalls
One common mistake is expecting Math.round() to always round down or up. It rounds to the nearest integer, so 4.5 rounds up to 5, but 4.4 rounds down to 4.
Another pitfall is trying to round to decimal places directly with these functions. They only work with whole numbers. To round to decimals, you need extra steps.
javascript
const num = 4.567; // Wrong: This will not round to 2 decimals console.log(Math.round(num)); // Outputs 5, not 4.57 // Right: Multiply, round, then divide const roundedTwoDecimals = Math.round(num * 100) / 100; console.log(roundedTwoDecimals); // Outputs 4.57
Output
5
4.57
Quick Reference
| Function | Description | Example | Output |
|---|---|---|---|
| Math.round() | Rounds to nearest integer | Math.round(4.5) | 5 |
| Math.floor() | Rounds down to nearest integer | Math.floor(4.9) | 4 |
| Math.ceil() | Rounds up to nearest integer | Math.ceil(4.1) | 5 |
Key Takeaways
Use Math.round() to round numbers to the nearest integer.
Use Math.floor() to always round down and Math.ceil() to always round up.
To round to decimal places, multiply, round, then divide.
Math.round() does not always round down or up; it rounds to the nearest integer.
These functions only work with numbers, not strings or other types.