JavaScript Math.trunc() strips the fractional part of a number and returns the integer portion, always moving toward zero (unlike Math.floor, which moves toward negative infinity on negatives). Use it when you want predictable truncation without implicit string coercion. For flooring toward negative infinity specifically, compare with JavaScript Math.floor.
Environment: Node.js v20.18.2. Each snippet is plain JavaScript; the line after it states the expected console output.
Math.trunc Syntax
Math.trunc(value)Math.trunc() removes digits after the decimal point. It does not round up or down by value; it moves toward zero.
Method 1: Truncate a Positive Number
console.log(Math.trunc(13.89));You should see one line logging 13.
Method 2: Truncate a Negative Number
console.log(Math.trunc(-13.89));You should see one line logging -13.
This is why Math.trunc() differs from Math.floor() for negative numbers.
Method 3: Compare Math.trunc() and Math.floor()
console.log(Math.trunc(-3.9));
console.log(Math.floor(-3.9));You should see 2 lines, in order: -3, -4.
Math.trunc() removes the fraction. Math.floor() rounds down toward negative infinity.
Method 4: Handle Invalid Values
console.log(Math.trunc("hello"));You should see one line logging NaN.
Common Questions About Math.trunc
What does Math.trunc do?
It removes fractional digits and returns the integer part of a number.
Does Math.trunc round toward zero?
Yes. Math.trunc(3.9) returns 3, and Math.trunc(-3.9) returns -3.
How is Math.trunc different from Math.floor?
For positive numbers they often match. For negative numbers, Math.floor(-3.9) returns -4, while Math.trunc(-3.9) returns -3.
Summary
Math.trunc drops the fraction toward zero—for negatives it differs from Math.floor, which always moves toward -Infinity.
JavaScript Math.trunc() is the built-in way to truncate a number by removing fractional digits. Use it when you need the integer part of a value and want rounding toward zero. It is especially useful for integer division and numeric cleanup where Math.floor() would be wrong for negative numbers.
