javascript - javascript 如何处理大整数(超过 52 位)?

标签 javascript node.js integer

考虑这段代码( Node v5.0.0)

const a = Math.pow(2, 53)
const b = Math.pow(2, 53) + 1
const c = Math.pow(2, 53) + 2

console.log(a === b) // true
console.log(a === c) // false

为什么 a === b 为真?

javascript 可以处理的最大整数值是多少?

我正在实现最大为 2^64 的随机整数生成器。有什么我应该注意的陷阱吗?

最佳答案

How javascript treat large integers?

JS 没有整数。 JS 数字是 64 位 float 。它们存储为尾数和指数。

精度由尾数给出,大小由指数给出。

如果您的数字需要比尾数中存储的更精确,最低有效位将被 chop 。

9007199254740992; // 9007199254740992
(9007199254740992).toString(2);
// "100000000000000000000000000000000000000000000000000000"
//  \        \                    ...                   /\
//   1        10                                      53  54
// The 54-th is not stored, but is not a problem because it's 0

9007199254740993; // 9007199254740992
(9007199254740993).toString(2);
// "100000000000000000000000000000000000000000000000000000"
//  \        \                    ...                   /\
//   1        10                                      53  54
// The 54-th bit should be 1, but the mantissa only has 53 bits!

9007199254740994; // 9007199254740994
(9007199254740994).toString(2);
// "100000000000000000000000000000000000000000000000000010"
//  \        \                    ...                   /\
//   1        10                                      53  54
// The 54-th is not stored, but is not a problem because it's 0

然后,您可以存储所有这些整数:

-9007199254740992, -9007199254740991, ..., 9007199254740991, 9007199254740992

第二个称为 minimum safe integer :

The value of Number.MIN_SAFE_INTEGER is the smallest integer n such that n and n − 1 are both exactly representable as a Number value.

The value of Number.MIN_SAFE_INTEGER is −9007199254740991 (−(253−1)).

倒数第二个叫做 maximum safe integer :

The value of Number.MAX_SAFE_INTEGER is the largest integer n such that n and n + 1 are both exactly representable as a Number value.

The value of Number.MAX_SAFE_INTEGER is 9007199254740991 (253−1).

关于javascript - javascript 如何处理大整数(超过 52 位)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52356673/

相关文章:

javascript - 如何让 DirectionService 在 map 上显示路线(Google map API)?

javascript - Jquery Ajax - 发布巨大的字符串值

javascript - Nodejs与C++程序通信?

node.js - Nodejs错误: libcouchbase. so.2:无法打开共享对象文件:没有那个文件或目录

java - 为什么 Java 8 引入了 *Integer.sum(int a, int b)*

java - java中十六进制字符串到整数解析异常处理

javascript - $timeout 函数中的 AngularJS 'this' 引用不起作用

javascript - src 和 dist 文件夹的作用是什么?

node.js - 在 Oracle linux 中为 nodejs 应用程序创建服务

iphone - 将 int 转换为 NSInteger