数字为999999999999999时的计算

Calculation when number is 999999999999999

看完#magically-increasing-numbers,

所以我想知道如果用 JS 制作 计算器 用户如何输入 大数字9999999999999999

const result = 9999999999999999 + 2
console.log(result)

正确的结果应该是10000000000000001而不是10000000000000002

我试过 Number() 甚至 parseFloat() 但还是不行。

我们该如何处理?

正如您已经发现的那样,您 运行 遇到了浮点数精度有限的问题,因为您的数字在 运行ge 的“安全整数”存储范围之外全精度(大于 Number.MAX_SAFE_INTEGER = 2^53 - 1)。

如果您只需要整数,native BigInt type 就可以正常工作(只要您注意以正确的方式将 to/from 转换为 BigInt):

const result = 9999999999999999n + 2n
console.log(result) // 10000000000000001n (not printed in Stack Overflow somehow)

如果您也需要小数,那么您将需要一个处理任意精度大小数算术的库,例如 bignumber.js,仅举其中之一。