JavaScript provides four built-in Math methods for rounding numbers, each with specific use cases.
Standard rounding (5+ up)
Math.round(4.7) → 5
Always rounds UP
Math.ceil(4.1) → 5
Always rounds DOWN
Math.floor(4.9) → 4
Removes decimals
Math.trunc(4.9) → 4
Rounds to the nearest integer using standard rules (0.5 and above rounds up).
Math.round(4.2); // 4
Math.round(4.5); // 5
Math.round(4.7); // 5
Math.round(-4.5); // -4
JavaScript doesn't have built-in decimal place rounding, but we can use this technique:
// Round to 2 decimal places
function roundToTwo(num) {
return Math.round(num * 100) / 100;
}
roundToTwo(3.14159); // 3.14
roundToTwo(12.567); // 12.57
// Generic function for any decimal places
function roundToDecimals(num, decimals) {
const multiplier = 10 ** decimals;
return Math.round(num * multiplier) / multiplier;
}
roundToDecimals(3.14159, 3); // 3.142
Math.ceil(4.1); // 5
Math.ceil(4.5); // 5
Math.ceil(4.9); // 5
Use for: Inventory calculations, package quantities, staffing needs
Math.floor(4.1); // 4
Math.floor(4.5); // 4
Math.floor(4.9); // 4
Use for: Age calculations, page numbers, completed units
const num = 3.14159;
num.toFixed(2); // "3.14" (string)
// Convert back to number
parseFloat(num.toFixed(2)); // 3.14 (number)
⚠️ Note: toFixed() returns a STRING, not a number. Use parseFloat() if you need a number.
// Example 1: Shopping cart total
const price = 19.99;
const tax = 0.0875;
const total = Math.round((price * (1 + tax)) * 100) / 100;
console.log(total); // 21.74
// Example 2: Calculate boxes needed
const items = 47.3;
const boxesNeeded = Math.ceil(items);
console.log(boxesNeeded); // 48
// Example 3: Calculate age from years
const years = 25.9;
const age = Math.floor(years);
console.log(age); // 25
| Value | Math.round() | Math.ceil() | Math.floor() | Math.trunc() |
|---|---|---|---|---|
| 4.2 | 4 | 5 | 4 | 4 |
| 4.5 | 5 | 5 | 4 | 4 |
| 4.9 | 5 | 5 | 4 | 4 |
Math.round(num)
Math.ceil(num)
Math.floor(num)
Math.round(n*100)/100