What's the Math.trunc() Alternative for BigInt Values in JavaScript?

Find out about bigint Math.trunc() alternative

The JavaScript Math.trunc() method only works on the number primitive values, and not on the bigint primitive values:

// TypeError: Cannot convert a BigInt value to a number

In fact, bigint values have no need for a "truncate" (or "trunc") method because:

  1. Bigint values are integers, and as such do not have a fraction part to "truncate" (or remove);
  2. Operations involving bigint values that produce a fractional result (such as division) are automatically truncated, and do not return any fractional digits.

For example:

// ES10+
const truncated = 10n / 4n;

console.log(truncated); // 2n (and not 2.5n)

The "n" at the end of a number merely suggests that the number is a bigint primitive.

Hope you found this post useful. It was published . Please show your love and support by sharing this post.