JavaScript 中的大整数(更多的是 2^53-1)

发布于 2024-09-16 14:33:40 字数 58 浏览 5 评论 0原文

在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

林空鹿饮溪 2024-09-23 14:33:40

你可以看一下这个实现。您还可能会发现其他实现很有用。

You may take a look at this implementation. You may also find other implementations useful.

初心未许 2024-09-23 14:33:40

您只需使用 JS 原生 BigInt于 2019 年被 JS 接受,并作为 ES2020 的一部分发布),这是一个数字原语使用不适合原始 Number 类型的整数。在原始形式中,它使用 n 后缀,并与常规数字支持的所有运算符一起使用,但具有显式整数逻辑。例如1n/3n0n

另请注意,这是与 Number 不同的原语,因此即使对于“安全”数字,n 版本也不会严格等于“普通”数字数字:

const a = 1n;
const b = 1;
console.log(a === b); // false
try {
  console.log(a + b); // TypeError, you can't add a Number to a BigInt
} catch (e) {}
console.log(a + BigInt(b)); // 2n

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 the n suffix and works with all operators that regular numbers support, but with explicit integer logic. E.g. 1n/3n is 0n.

Also note that this is a different primitive from Number, so even for "safe" numbers the n version will not strictly equal the "plain" number:

const a = 1n;
const b = 1;
console.log(a === b); // false
try {
  console.log(a + b); // TypeError, you can't add a Number to a BigInt
} catch (e) {}
console.log(a + BigInt(b)); // 2n

南风起 2024-09-23 14:33:40

我过去使用过的另一个选项是通过 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文