How to Convert BigInt to Number type in Javascript?

This blog post provides a walkthrough of several examples for converting BigInt types to various numeric types such as Float, Integer, Hexadecimal, Octal, and Binary.

ES10 introduced the bigint data type, capable of storing arbitrary-precision numbers exceeding 2 to the power of 53 minus 1. Unlike regular numbers, which are handled by the Number datatype and can store values up to 2 to the power of 53 minus 1.

How to Convert BigInt to Number in JavaScript?

There are various methods to convert a BigInt to numeric values.

  • Using the number constructor

  • Using the parseInt method

  • Using Number constructor The number constructor accepts an object type and returns numeric data.

    Syntax:

    Number(Object);
    or
    new Number(object);
    

    The constructor accepts BigInt data and returns numbers.

    Here’s an example of parsing BigInt to a number:

    const bigIntValue = BigInt(147);
    const bigIntValue1 = BigInt(24n);
    
    const number = Number(bigIntValue);
    const number1 = Number(bigIntValue1);
    
    console.log(typeof bigIntValue1); // bigint
    console.log(typeof number1); // number
    console.log(typeof bigIntValue); // bigint
    console.log(typeof number); // number
    
    console.log(bigIntValue); // 147n
    console.log(bigIntValue1); // 24n
    console.log(number); // 147
    console.log(number1); // 24
    
  • Using parseInt method

The parseInt() method parses the object and returns a numeric value.

Syntax

parseInt(object, base);

Return and parameters:

The object is the data to convert to a numeric value, and the base can be 2 for binary, 8 for octal, or 16 for hexadecimal. If the base is omitted, the method checks if the object starts with 0x and treats it as a hexadecimal conversion, or if it starts with 0, it’s treated as octal. Otherwise, it’s treated as a decimal value.

const bigIntValue = BigInt(7);
const bigIntValue1 = BigInt(4n);

const number = parseInt(bigIntValue);
const number1 = parseInt(bigIntValue1);

console.log(typeof bigIntValue1); // bigint
console.log(typeof number1); // number
console.log(typeof bigIntValue); // bigint
console.log(typeof number); // number

console.log(bigIntValue); // 7n
console.log(bigIntValue1); // 4n
console.log(number); // 7
console.log(number1); // 4

The above methods work in TypeScript as well.

Conclusion

In conclusion, this post covers various methods to convert a bigint to numbers using the Number constructor and the parseInt method.