Skip to content
Tutorials Center
My learning

Topics

JavaScript Reference ยท Math

Math.trunc() method

Reference for JavaScript Math.trunc(): remove the fractional part of a number, how it differs from floor, round and parseInt, plus -0, strings and edge cases.

Math.trunc() cuts off the fractional part of a number and returns the integer part, whatever the sign. Math.trunc(4.9) is 4 and Math.trunc(-4.9) is -4. It always moves toward zero, so it never rounds anything up or down by value.

That makes it different from Math.floor(), which moves toward negative infinity. For positive numbers they match; for negative numbers they do not.

JavaScript
Math.trunc(7.89);    // 7
Math.trunc(-7.89);   // -7

Try it

JS Truncating toward zero

Press Run (or Ctrl + Enter) to see the console output here.

No output.

JS Whole and fractional parts, coercion

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Syntax

JavaScript
Math.trunc(x)
Name Description
x A number. Other values are converted to a number first.

Return value: the integer part of x. NaN stays NaN, Infinity and -Infinity are unchanged, and results between -1 and 0 are -0.

Exceptions: a TypeError for a BigInt or a Symbol.

Usage notes

  • Truncation, not rounding. Math.trunc(0.99) is 0. If you want the nearest integer, use Math.round().
  • Compared with floor: the two differ only for negative non-integers. Use trunc when "ignore the decimals" is the meaning, for example when splitting a number into whole and fractional parts.
  • Compared with parseInt(): parseInt converts its argument to a string first, so parseInt(0.0000005) is 5 (from "5e-7") and parseInt(1e21) is 1. Math.trunc works on the number itself and is the correct choice for numbers.
  • Compared with x | 0 or ~~x: the bitwise tricks first convert to a 32-bit integer, so they wrap for values beyond about 2.1 billion. Math.trunc handles the full range.
  • Negative zero: Math.trunc(-0.5) returns -0. It equals 0 with ===, though consoles may print it as -0.
  • Fractional part: x - Math.trunc(x) keeps the sign of x and inherits floating-point error (see floating-point numbers).
  • Strings are coerced, so Math.trunc("9.99") is 9, and Math.trunc("x") is NaN.

Browser support

Math.trunc() is available in all current browsers and runtimes. It was added in ES2015, so Internet Explorer did not support it.