rounding
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`.
Math.sign(x) Parameters & edge cases
| Case | Behavior |
|---|---|
| x | Any numeric value; non-numbers are coerced first |
| signed zero | Math.sign(-0) returns -0, and Math.sign(0) returns 0 — distinct values |
| NaN | Math.sign(NaN) returns NaN — always check with Number.isNaN before using |
Examples
console.log(Math.sign(5)); // 1 Positive numbers return 1.
console.log(Math.sign(-5)); // -1 Negative numbers return -1.
console.log(Math.sign(0)); // 0 Positive zero returns 0.
console.log(Math.sign(-0)); // -0 Negative zero returns -0 (===0 is true, but Object.is(-0,0) is false).
Gotcha
Math.sign returns 5 possible values (1, -1, 0, -0, NaN), not just three. If you need a boolean-ish direction, coerce with `Math.sign(x) || 0` to collapse -0 to 0.
Related
Math.abs
Returns the absolute value of a number — its distance from zero without regard to sign. Useful for differences, magnitudes, and tolerance checks.
Math.trunc
Returns the integer part of a number by removing any fractional digits — rounding toward zero. Introduced in ES2015.
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.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.