rounding
Math.floor
Returns the largest integer less than or equal to a given number (rounds toward -Infinity). Always moves left on the number line.
Math.floor(x) Parameters & edge cases
| Case | Behavior |
|---|---|
| x | The number to floor; strings are coerced to numbers first |
| negative values | Floors AWAY from zero: Math.floor(-1.1) === -2 (not -1) |
| integers | Already-integer inputs are returned unchanged, including -0 |
Examples
console.log(Math.floor(2.9)); // 2 Drops the fractional part for positives.
console.log(Math.floor(-2.1)); // -3 Rounds toward -Infinity, so -2.1 becomes -3 (differs from Math.trunc).
console.log(Math.floor(5)); // 5 Whole numbers pass through unchanged.
console.log(Math.floor(Math.random() * 10)); // 0-9 Classic idiom for a random integer in [0, 10).
Gotcha
Math.floor(-0) === -0, not 0 — the sign is preserved. Use `| 0` for a fast floor of positive 32-bit numbers, but it truncates for negatives.
Related
Math.ceil
Returns the smallest integer greater than or equal to a given number (rounds toward +Infinity). Always moves right on the number line.
Math.round
Returns the value of a number rounded to the nearest integer. Halfway values (.5) always round toward +Infinity, not away from zero.
Math.trunc
Returns the integer part of a number by removing any fractional digits — rounding toward zero. Introduced in ES2015.
Math.sign
Returns the sign of a number as 1, -1, 0, -0, or NaN. Introduced in ES2015 as a compact replacement for the ternary `x > 0 ? 1 : x < 0 ? -1 : 0`.