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

← All JS Math methods · Array methods