一个数字在不损失精度的情况下可以达到的 JavaScript 的最高整数值是多少? [英] What is JavaScript's highest integer value that a number can go to without losing precision?
问题描述
这是由语言定义的吗?有定义的最大值吗?不同浏览器有区别吗?
Is this defined by the language? Is there a defined maximum? Is it different in different browsers?
推荐答案
JavaScript 有两种数字类型:Number
和 BigInt
.
JavaScript has two number types: Number
and BigInt
.
最常用的数字类型 Number
是 64 位浮点数 IEEE 754 编号.
The most frequently-used number type, Number
, is a 64-bit floating point IEEE 754 number.
这种类型的最大精确整数值是 Number.MAX_SAFE_INTEGER
,即:
The largest exact integral value of this type is Number.MAX_SAFE_INTEGER
, which is:
- 253-1 或
- +/- 9,007,199,254,740,991,或
- 九千万亿七万亿一千九百九十二亿五千四百万七十万九百九十一
从正确的角度来看:一千万亿字节是 PB(或一千 TB).
To put this in perspective: one quadrillion bytes is a petabyte (or one thousand terabytes).
这里的安全"是指准确表示整数并正确比较它们的能力.
"Safe" in this context refers to the ability to represent integers exactly and to correctly compare them.
注意所有大小为no的正负整数大于 253 可以用 Number
类型表示(实际上,整数 0 有两种表示形式,+0 和 -0).
Note that all the positive and negative integers whose magnitude is no greater than 253 are representable in the
Number
type (indeed, the integer 0 has two representations, +0 and -0).
要安全地使用大于此值的整数,您需要使用 BigInt
,没有上限.
To safely use integers larger than this, you need to use BigInt
, which has no upper bound.
请注意,按位运算符和移位运算符对 32 位整数进行运算,因此在这种情况下,最大安全整数为 231-1,即 2,147,483,647.
Note that the bitwise operators and shift operators operate on 32-bit integers, so in that case, the max safe integer is 231-1, or 2,147,483,647.
const log = console.log
var x = 9007199254740992
var y = -x
log(x == x + 1) // true !
log(y == y - 1) // also true !
// Arithmetic operators work, but bitwise/shifts only operate on int32:
log(x / 2) // 4503599627370496
log(x >> 1) // 0
log(x | 1) // 1
关于数字 9,007,199,254,740,992 的技术说明:这个值有一个精确的 IEEE-754 表示,你可以从一个变量中分配和读取这个值,所以对于非常小心选择的应用程序在小于或等于此值的整数域中,您可以将其视为最大值.
Technical note on the subject of the number 9,007,199,254,740,992: There is an exact IEEE-754 representation of this value, and you can assign and read this value from a variable, so for very carefully chosen applications in the domain of integers less than or equal to this value, you could treat this as a maximum value.
在一般情况下,您必须将此 IEEE-754 值视为不准确,因为它是对逻辑值 9,007,199,254,740,992 还是 9,007,199,254,740,993 进行编码是不明确的.
In the general case, you must treat this IEEE-754 value as inexact, because it is ambiguous whether it is encoding the logical value 9,007,199,254,740,992 or 9,007,199,254,740,993.
这篇关于一个数字在不损失精度的情况下可以达到的 JavaScript 的最高整数值是多少?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!