JavaScript 中的大整数(更多的是 2^53-1)
在 javascript 中处理大整数的一般原则是什么?就像在 bigint 库中一样?我自己怎么做?
What is general principals to operate with large integers in javascript? Like in libraries for bigint? How i do it by myself?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
你可以看一下这个实现。您还可能会发现其他实现很有用。
You may take a look at this implementation. You may also find other implementations useful.
您只需使用 JS 原生 BigInt (于 2019 年被 JS 接受,并作为 ES2020 的一部分发布),这是一个数字原语使用不适合原始
Number
类型的整数。在原始形式中,它使用n
后缀,并与常规数字支持的所有运算符一起使用,但具有显式整数逻辑。例如1n/3n
是0n
。另请注意,这是与
Number
不同的原语,因此即使对于“安全”数字,n
版本也不会严格等于“普通”数字数字:You just use the JS-native BigInt (accepted into JS in 2019 and released as part of ES2020), which is a number primitive for working with integers that don't fit in the original
Number
type. In primitive form it uses then
suffix and works with all operators that regular numbers support, but with explicit integer logic. E.g.1n/3n
is0n
.Also note that this is a different primitive from
Number
, so even for "safe" numbers then
version will not strictly equal the "plain" number:我过去使用过的另一个选项是通过 jsonp 将这些操作交给计算服务器。如果您正在处理如此大的数字,您可能希望这可以为您带来更高的性能和精度。
Another option I've used in the past, is to hand off those operations to a calculation server via jsonp. If you're working with such large numbers, you likely want the improved performance and precision this can give you.
JavaScript 现在有
BigInt
。参考文献:
https://github.com/tc39/proposal-bigint
https://developer.mozilla.org/en-US/docs/Web /JavaScript/Reference/Global_Objects/BigInt
JavaScript has
BigInt
now.References:
https://github.com/tc39/proposal-bigint
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt