How to Convert BigInt to Number in JavaScript

In JavaScript, a BigInt is a built-in object that provides a way to represent whole numbers larger than 2^53 – 1, which is the largest number JavaScript can reliably represent with the Number primitive. Since BigInt and Number are two different types, they are not directly interchangeable.

To convert BigInt to Number in JavaScript, you can use the Number() constructor.

const bigIntValue = BigInt("123456789012345678901234567890");

const numberValue = Number(bigIntValue);

console.log(numberValue);

Output

1.2345678901234568e+29

When converting a BigInt to a Number in JavaScript, it’s essential to ensure that the value lies within the safe integer range.

safe integer range

If the BigInt value is outside this range, the conversion to a Number could lead to unexpected results due to a loss of precision.

To ensure safe conversion, you can use a check like this:

const bigIntValue = BigInt("1234567890123456789");

if (bigIntValue >= BigInt(Number.MIN_SAFE_INTEGER) && bigIntValue <= BigInt(Number.MAX_SAFE_INTEGER)) {
  const numberValue = Number(bigIntValue);
  console.log(numberValue);
} else {
  console.warn("BigInt value is out of the safe integer range for conversion.");
}

Output

BigInt value is out of the safe integer range for conversion.

That’s it!

Related posts

JavaScript Number to BigInt