gpt4 book ai didi

javascript - Javascript 中大数的精度

转载 作者:行者123 更新时间:2023-11-28 14:20:54 25 4
gpt4 key购买 nike

我正在练习用阶乘显示大量数字。问题是当结果太大时它总是自动舍入。这是一个例子:

function extraLongFactorials(n) {
const rs = [...Array(n)].reduce((a, b, i) => a*(i+1), 1);
console.log(rs);
}

extraLongFactorials(25);

上述代码的结果是:

1.5511210043330986e+25

当预期输出为

15511210043330985984000000

我尝试使用 toFixed()toLocaleString('fullwide', {useGrouping: false}) 但两者都给出了错误的输出。

15511210043330986000000000

有人知道如何处理这种情况吗?

最佳答案

这应该适用于当前支持 BigInt 的所有浏览器。请注意,BigInt 和 Number 之间的操作不能混合,因此我们必须首先从 BigInt 开始(注意 1n 处的 n 标志)。 StackSnippet 需要 rs.toString() ,因为它伪造了控制台,而伪造的控制台仍然不知道如何从 ES6+ 打印几种较新的数据类型;真正的控制台会知道如何正常打印 BigInt。

function extraLongFactorials(n) {
const rs = [...Array(n)].reduce((a, b, i) => a*(BigInt(i+1)), 1n)
console.log(rs.toString())
}

extraLongFactorials(25)

如果您的浏览器支持 BigInt,那么...那么...获取更好的浏览器(或者使用像 this 这样的库,我想。但是获取更好的浏览器。 )

关于javascript - Javascript 中大数的精度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55235429/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com