rounding
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.round(x) Parameters & edge cases
| Case | Behavior |
|---|---|
| x | The number to round; non-numeric input is coerced (NaN, null, undefined) |
| half-up rule | Ties break toward +Infinity: 0.5 → 1, but -0.5 → 0 (not -1) |
| NaN input | Returns NaN unchanged; Infinity and -Infinity are returned as-is |
Examples
console.log(Math.round(2.5)); // 3 Standard half-up rounding for positive values.
console.log(Math.round(-2.5)); // -2 Ties break toward +Infinity, so -2.5 rounds up to -2, not down to -3.
console.log(Math.round(2.49)); // 2 Below the halfway point rounds down as expected.
console.log(Math.round(-0.5)); // -0 Notorious gotcha: Math.round preserves negative zero for inputs in [-0.5, -0). `Math.round(-0.5) === 0` is `true` (since -0 === 0), but `Object.is(Math.round(-0.5), -0)` is also `true`.
Gotcha
Math.round is not symmetric around zero: Math.round(0.5) === 1 but Math.round(-0.5) is -0 (=== 0 but Object.is-distinct from +0). For financial rounding use a toFixed + parseFloat pattern or a dedicated helper.
Related
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.ceil
Returns the smallest integer greater than or equal to a given number (rounds toward +Infinity). Always moves right on the number line.
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`.