【踩坑】JS/TS 整数明明没有超过 Number.MAX_VALUE,为啥精度还是丢失了?

发布时间 2023-09-26 17:01:05作者: bakabird1998

代码

function calcKey(props) {
    return props.reduce((key, prop, index) => {
        const code = prop[0] * (15 + 1) + prop[1];
        console.log(code);
        console.log(key);
        return key  + code * Math.pow(1000, index) ;
    }, 0);
}

function calcByStr(str) {
    return calcKey(str.trim().split(" ").map(item => item.split(",").map(i => parseInt(i))));
}

calcByStr("1,11 3,1 1,3 4,6 4,11 8,1 8,11 8,13 ")

运行结果

image

如图在标黄的部分,key 的尾部本应该是 ....027,却变成了 020,发生了精度丢失。
但 Number.MAX_VALUE 明明远大于我们的 129075070019049020 。

image

这是为什么呢?

参考 Javascript可以保存的最大数值_js最大整数_梦想是坚持的博客-CSDN博客

JS中实际上:整数
整数 ±2^53 = 9007199254740992
基本上超过16位整数就无法精确地表示了 超过这个最大值,所有的奇数都会+1或者-1变成偶数,无法准确赋值。