How to convert BigInt to Number in JavaScript?

JavascriptBigintEcmascript Next

Javascript Problem Overview


I found myself in the situation where I wanted to convert a BigInt value to a Number value. Knowing that my value is a safe integer, how can I convert it?

Javascript Solutions


Solution 1 - Javascript

Turns out it's as easy as passing it to the Number constructor:

const myBigInt = BigInt(10);  // `10n` also works
const myNumber = Number(myBigInt);

Of course, you should bear in mind that your BigInt value must be within [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER] for the conversion to work properly, as stated in the question.

Solution 2 - Javascript

You can use parseInt or Number

const large =  BigInt(309);
const b = parseInt(large);
console.log(b);
const n = Number(large);
console.log(n);

Solution 3 - Javascript

You should use either of the static methods:

BigInt.asIntN() - Clamps a BigInt value to a signed integer value, and returns that value. BigInt.asUintN() - Clamps a BigInt value to an unsigned integer value, and returns that value.

as documented here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt#static_methods

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionLucio PaivaView Question on Stackoverflow
Solution 1 - JavascriptLucio PaivaView Answer on Stackoverflow
Solution 2 - JavascriptI_Al-thamaryView Answer on Stackoverflow
Solution 3 - Javascriptzr0gravity7View Answer on Stackoverflow