Monday, March 9, 2020

Typescript/JavaScript example - Convert BigInt to Number type

In this blog post, I will give several examples of Converting BigInt type to numeric types -  Float, Integer, Hexa, Octal, Binary.

Typescript/JavaScript example - Convert BigInt to Number type
Es10 introduced bigint new data type that stores arbitrary of 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 following different ways we can convert bigint to numeric values.
  • number constructor
  • parseInt method

using Number constructor

Number constructor accepts of object type and returns number data.
Syntax
Number(Object)
or 
new Number(object)
constructor takes bigint data and returns number.
Following is an example for parse bigint to 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 

parseInt() method parses and object returns numeric value.
Syntax
parseInt(object,base)
return and parameters
Object is the actual data to convert to numeric value base is 2-binary, 8-octal 16- hex types if base is omitted, checks object starts with 0x treat as Hexa conversion, stars with 0 as octal conversion if starts other than the above, treat as 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.

Related article


EmoticonEmoticon