Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert BigInt to Number in JavaScript?

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?

like image 850
Lucio Paiva Avatar asked Dec 29 '18 15:12

Lucio Paiva


People also ask

How do you convert BigInt to INT?

BigInteger. intValue() converts this BigInteger to an int. This conversion is analogous to a narrowing primitive conversion from long to int.

What is a BigInt in JavaScript?

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.

Does JavaScript support BigInt?

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.


3 Answers

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.

like image 170
Lucio Paiva Avatar answered Oct 08 '22 07:10

Lucio Paiva


You can use parseInt or Number

const large =  BigInt(309);
const b = parseInt(large);
console.log(b);
const n = Number(large);
console.log(n);
like image 45
I_Al-thamary Avatar answered Oct 08 '22 05:10

I_Al-thamary


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

like image 2
zr0gravity7 Avatar answered Oct 08 '22 06:10

zr0gravity7