The Math object has four ways to turn a decimal into a whole number. They behave differently, especially with negative numbers.
| Method | Rule |
|---|---|
Math.round(x) | Nearest integer (.5 goes up) |
Math.floor(x) | Down, toward negative infinity |
Math.ceil(x) | Up, toward positive infinity |
Math.trunc(x) | Cut off the decimals |
console.log(Math.round(4.5)); // → 5
console.log(Math.round(4.4)); // → 4
console.log(Math.floor(4.9)); // → 4
console.log(Math.ceil(4.1)); // → 5
console.log(Math.trunc(4.9)); // → 4
Negative numbers
This is where they differ.
console.log(Math.round(-4.5)); // → -4
console.log(Math.floor(-4.1)); // → -5
console.log(Math.ceil(-4.9)); // → -4
console.log(Math.trunc(-4.9)); // → -4
floor always goes down (more negative), while trunc simply drops the decimals. Math.round(-4.5) is -4, because .5 rounds toward positive infinity.
Rounding to decimals
Math.round rounds to whole numbers only. To keep two decimals, multiply, round, divide, or use toFixed() for display.
const value = 3.14159;
console.log(Math.round(value * 100) / 100); // → 3.14
console.log(value.toFixed(2)); // → 3.14 (a string)
Typical uses
// How many pages for 23 items at 10 per page? (always round up)
console.log(Math.ceil(23 / 10)); // → 3
// Which row does item index 7 belong to, with 3 per row?
console.log(Math.floor(7 / 3)); // → 2
// Round a percentage
const done = 7, total = 9;
console.log(Math.round((done / total) * 100) + "%"); // → 78%
Pick by intent
ceil. Whole units that fit: floor. Nearest value: round. Drop decimals regardless of sign: trunc.