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.
Math.trunc(7.89); // 7 Math.trunc(-7.89); // -7
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
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)is0. If you want the nearest integer, useMath.round(). - Compared with
floor: the two differ only for negative non-integers. Usetruncwhen "ignore the decimals" is the meaning, for example when splitting a number into whole and fractional parts. - Compared with
parseInt():parseIntconverts its argument to a string first, soparseInt(0.0000005)is5(from"5e-7") andparseInt(1e21)is1.Math.truncworks on the number itself and is the correct choice for numbers. - Compared with
x | 0or~~x: the bitwise tricks first convert to a 32-bit integer, so they wrap for values beyond about 2.1 billion.Math.trunchandles the full range. - Negative zero:
Math.trunc(-0.5)returns-0. It equals0with===, though consoles may print it as-0. - Fractional part:
x - Math.trunc(x)keeps the sign ofxand inherits floating-point error (see floating-point numbers). - Strings are coerced, so
Math.trunc("9.99")is9, andMath.trunc("x")isNaN.
Browser support
Math.trunc() is available in all current browsers and runtimes. It was added in ES2015, so Internet Explorer did not support it.
Related
Math.floor(),Math.ceil(),Math.round(),parseInt()- Lessons: Math, Numbers