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?
BigInteger. intValue() converts this BigInteger to an int. This conversion is analogous to a narrowing primitive conversion from long to int.
BigInt is a special numeric type that provides support for integers of arbitrary length. A bigint is created by appending n to the end of an integer literal or by calling the function BigInt that creates bigints from strings, numbers etc.
BigInt is a built-in object in JavaScript that provides a way to represent whole numbers larger than 253-1. The largest number that JavaScript can reliably represent with the Number primitive is 253-1, which is represented by the MAX_SAFE_INTEGER constant.
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.
You can use parseInt
or Number
const large = BigInt(309);
const b = parseInt(large);
console.log(b);
const n = Number(large);
console.log(n);
Edit: see the discussion in the comments below as to why this answer is not correct. I am leaving the answer up regardless for disambiguation.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With