在 Node.js 中执行以下代码:
setTimeout(() => {
console.log('test')
}, 2147483647 + 1);
会提示:
(node:17462) TimeoutOverflowWarning: 2147483648 does not fit into a 32-bit signed integer.
Timeout duration was set to 1.
因为 js 的 single precision number 是用 32-bit 表示的,最大能表示 2147483647,不到 22 亿,setTimeout
只支持 32-bit 数字,如果给它提供了一个更大的数字,会一律视为 1,这会导致 setTimeout()
马上超时。
js 还有一个 Number.MAX_SAFE_INTEGER
变量,它的值是 9007199254740991
,超过 9000 万亿,这是 js 的 double precision number 的最大值,采用 64-bit 表示,是最大的安全整数。
超过 Number.MAX_SAFE_INTEGER
的数字不能使用 Number
对象,而是用 BigInt
,BigInt
的最大值取决于电脑的内存,如果内存无限大,BigInt
就没有最大值,或者说最大值就是无限。
之所以有 single precision 和 double precision 的区别,根据 stackoverflow 的一个回答和另一个回答,是为了更准确地表示 floating point number。所谓的 floating point number,其实就是小数,floating point 是小数点。
在 single precision number 中,小数点后只能精确到 7-8 位,而 double precision number 可以精确到 15-16 位,是 single 的两倍,即 double,这才是 double 的意思,而不是因为 64 是 32 的两倍。
相关文章: