Math.trunc()

ES6+

Returns the integer part of a number by removing any fractional digits.

Syntax

Math.trunc(x)

Parameters

x number

A number

Return Value

number

The integer part of the given number

Examples

JavaScript
console.log(Math.trunc(4.7));
console.log(Math.trunc(-4.7));
console.log(Math.trunc(0.123));
Output:
// 4 -4 0

📌 When to Use

Use Math.trunc() when you need to remove decimals without rounding, especially for negative numbers where the behavior differs from Math.floor().

⚠️ Common Mistakes

Using Math.trunc() in environments that do not support ES6 without a polyfill.

Confusing Math.trunc() with parseInt() - they behave differently with non-numeric strings.

✅ Best Practices

Use Math.trunc() instead of parseInt(x, 10) when you already have a number and just need to remove decimals.

For ES5 compatibility, use Math.floor() for positive numbers and Math.ceil() for negative numbers.

⚡ Performance Notes

Math.trunc() is faster than parseInt() for numeric values. The bitwise (x | 0) trick is faster but limited to 32-bit integers.

🌍 Real World Example

Video Timestamp Formatter

Convert video duration in seconds to hours:minutes:seconds format.

function formatDuration(totalSeconds) {
  const hours = Math.trunc(totalSeconds / 3600);
  const minutes = Math.trunc((totalSeconds % 3600) / 60);
  const seconds = Math.trunc(totalSeconds % 60);

  const pad = (n) => String(n).padStart(2, '0');

  if (hours > 0) {
    return `${hours}:${pad(minutes)}:${pad(seconds)}`;
  }
  return `${minutes}:${pad(seconds)}`;
}

console.log(formatDuration(3725.8)); // "1:02:05"
console.log(formatDuration(185.4));  // "3:05"

Related Methods