js精度丢失 es11新出BigInt 的可以解决 BigInt 可以表示任意精度格式的整数

//Number类型在超过9009199254740991后,计算结果即出现问题
const num1 = 90091992547409910;
console.log(num1 + 1); //90091992547409900

//BigInt 计算结果争取
const num2 = 90091992547409910n;
console.log(num2 + 1n); //90091992547409911n
//Number 类型不能表示大于 2 的 1024 次方的数值
let num3 = 9999;
for(let i = 0; i < 10; i++) {
    num3 = num3 * num3;
}
console.log(num3); //Infinity

//BigInt 类型可以表示任意位数的整数
let num4 = 9999n;
for(let i = 0n; i < 10n; i++) {
    num4 = num4 * num4;
}
console.log(num4); //一串超级长的数字,这里就不贴了

我们还可以使用 BigInt 对象来初始化 BigInt 实例:
console.log(BigInt(999)); // 999n 注意:没有 new 关键字!!!

需要说明的是,BigInt 和 Number 是两种数据类型,不能直接进行四则运算,不过可以进行比较操作。
console.log(99n == 99); //true
console.log(99n === 99); //false 
console.log(99n + 1);//TypeError: Cannot mix BigInt and other types, use explicit conversionss

  

原文地址:https://www.cnblogs.com/isuansuan/p/14035880.html