rounding
Math.trunc
Returns the integer part of a number by removing any fractional digits — rounding toward zero. Introduced in ES2015.
Math.trunc(x) Parameters & edge cases
| Case | Behavior |
|---|---|
| x | Number to truncate; strings coerce, NaN returns NaN |
| toward zero | Differs from Math.floor for negatives: trunc(-1.9) === -1, floor(-1.9) === -2 |
| ES2015+ | Not available in IE; polyfill with x < 0 ? Math.ceil(x) : Math.floor(x) |
Examples
console.log(Math.trunc(2.9)); // 2 Drops the fraction for positives — same as Math.floor here.
console.log(Math.trunc(-2.9)); // -2 Drops the fraction for negatives — differs from Math.floor which gives -3.
console.log(Math.trunc(0.001)); // 0 Very small numbers truncate to 0.
console.log(Math.trunc('42.7')); // 42 Strings are coerced to numbers before truncation.
Gotcha
Math.trunc is NOT the same as Math.floor for negative numbers. Bitwise `| 0` behaves like trunc but only works for values in the signed 32-bit range.
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.round
Returns the value of a number rounded to the nearest integer. Halfway values (.5) always round toward +Infinity, not away from zero.
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.ceil
Returns the smallest integer greater than or equal to a given number (rounds toward +Infinity). Always moves right on the number line.