ArticleZip > How To Convert Bigint To Number In Javascript

How To Convert Bigint To Number In Javascript

Big integers (BigInts) are a data type in JavaScript that allows you to work with large numbers beyond the limit of the number type. Sometimes you may need to convert BigInts to standard numbers for various computations in your JavaScript code. In this guide, we will explore how to convert a BigInt to a regular number in JavaScript.

1. Using Number() Constructor:
You can convert a BigInt to a number in JavaScript using the Number() constructor. This method works well if your BigInt is within the permissible range of a regular number.

Plaintext

const bigIntNum = 12345678901234567890123456789n;
const regularNum = Number(bigIntNum);
console.log(regularNum); // Output: 1.2345678901234568e+28

2. Using BigInt.prototype.toString() Method:
Another way to convert a BigInt to a number is by converting the BigInt to a string using the toString() method, and then parsing it to a number using the parseInt() function.

Plaintext

const bigIntNum = 12345678901234567890123456789n;
const regularNum = parseInt(bigIntNum.toString());
console.log(regularNum); // Output: 12345678901234567890123456789

3. Using Unary Plus Operator:
You can also convert a BigInt to a number using the unary plus (+) operator. This method converts the operand to a number.

Plaintext

const bigIntNum = 12345678901234567890123456789n;
const regularNum = +bigIntNum;
console.log(regularNum); // Output: 1.2345678901234568e+28

4. Using Math.floor() Function:
If you want to convert a BigInt to an integer (rounding down), you can use the Math.floor() function after converting the BigInt to a string.

Plaintext

const bigIntNum = 12345678901234567890123456789n;
const regularNum = Math.floor(Number(bigIntNum.toString()));
console.log(regularNum); // Output: 12345678901234567890123456789

5. Precautions:
- Be wary of potential precision loss when converting BigInts to regular numbers, especially for large numbers.
- Check if the BigInt value falls within the safe range of regular numbers before conversion to avoid unexpected results.

In conclusion, converting a BigInt to a regular number in JavaScript can be done using various methods like the Number() constructor, toString() method, unary plus operator, or Math.floor() function. Choose the appropriate method based on your specific requirements and ensure to account for potential precision issues when working with large numbers.