How to Convert BigInt to Number type in Typescript?
- Admin
- Sep 20, 2023
- Javascript Typescript Javascript-convert
In this blog post, I will give several examples for Converting BigInt type to numeric types - Float, Integer, Hexa, Octal, Binary.
Es10 introduced bigint new data type that stores arbitrary-precision numbers. It can store values greater than 2 power 53 -1
Numbers are numeric data of Number datatype, store the data up to 2 power 53-1.
How to Convert BigInt to Number in Javascript?
There are the following different ways we can convert BigInt
to numeric
values.
- number constructor
- parseInt method
Convert BigInt to Number using typescript Number constructor
Number constructor accepts object type and returns number data.
Syntax:
Number(Object);
or;
new Number(object);
the constructor takes BigInt
data and returns numbers.
Following is an example for parse 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
Convert BigInt to Number using typescript use parseInt method
parseInt()
method parses and object returns numeric value.
Syntax
parseInt(object, base);
return and parameters
The object is the actual data to convert to numeric value base is 2-binary, 8-octal 16-hex types.
if the base is omitted, It checks object starts with 0x treat as Hexa conversion, stars with 0 as an octal conversion if starts other than the above, treat 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 same above works in typescript.
Conclusion
To summarize, Learn how to Convert bigint to number in multiple using the Number constructor and parseInt method.