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

Find out about bigint Math.sign() alternative

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

// TypeError: Cannot convert a BigInt value to a number
Math.sign(2n);

Therefore, you can implement a custom "sign" method for bigint numbers instead, which would return similar values to the Math.sign() method, i.e.:

  • Return 0 if value is 0;
  • Return -0 if value is -0;
  • Return 1 if value is greater than 0;
  • Return -1 if value is less than 0.

You can implement this for bigint numbers in the following way:

// ES10+
const sign = (val) => {
    if (val === 0n) {
        return val;
    }

    return (val < 0n) ? -1n : 1n;
};

Please note that if the value is -0n, then 0n is returned (instead of -0n). This is due to the way browsers handle the -0n as a return value.

For example, you could use the custom sign function (with bigint values) in the following way:

console.log(sign(0n)); // 0n
console.log(sign(-0n)); // 0n
console.log(sign(10n)); // 1n
console.log(sign(-10n)); // -1n
console.log(sign(18014398509481982n)); // 1n
console.log(sign(-18014398509481982n)); // -1n
console.log(sign(BigInt(Number.MAX_SAFE_INTEGER))); // 1n
console.log(sign(BigInt(-Number.MAX_SAFE_INTEGER))); // -1n

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