如何在Javascript中把BigInt转换为Number

3,317 阅读1分钟

在这篇博文中,我将给出几个将BigInt类型转换为数字类型的例子 - Float, Integer, Hexa, Octal, Binary。

Es10引入了bigint这种新的数据类型,用于存储任意精度的数字。它可以存储大于2次方53-1的数值
数字是Number数据类型的数值数据,可以存储2次方53-1的数据。

如何在Javascript中把BigInt转换为Number

我们可以通过以下不同的方式将bigint转换为数字值。

使用Number构造函数

Number构造函数接受对象类型并返回数字数据。

语法

Number(Object)  
or   
new Number(object)  

构造函数接受bigint数据并返回数字。

下面是一个将bigint转换成数字的例子。

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  

使用parseInt方法

parseInt()方法解析对象并返回数字值。
语法

parseInt(object,base)  

返回和参数
对象是要转换为数值的实际数据 基数是2-二进制、8-八进制、16-十六进制类型 如果省略基数,检查对象以0x开头,作为六进制转换,以0开头作为八进制转换 如果以上述以外的开头,作为十进制值处理

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  

上述内容在typescript中同样适用。