Home >Web Front-end >JS Tutorial >What's the Highest Integer JavaScript Can Represent Without Losing Precision?
JavaScript's Highest Integer Value Without Precision Loss
JavaScript's capacity to represent integers is bounded by the representation of numbers in the language.
Number Type
The ubiquitous Number type in JavaScript is a 64-bit floating-point number based on IEEE 754. The largest exact integral value this type can represent without precision loss is Number.MAX_SAFE_INTEGER.
2<sup>53</sup> - 1 = 9,007,199,254,740,991
BigInt Type
For integers larger than Number.MAX_SAFE_INTEGER, JavaScript provides the BigInt type, which holds no upper bound.
Bitwise Operators
Note that bitwise operators and shift operators operate on 32-bit integers, resulting in a different maximum safe integer:
2<sup>31</sup> - 1 = 2,147,483,647
Comparison
Safe integers (those below Number.MAX_SAFE_INTEGER) can be correctly compared using equality operators:
const x = 9007199254740992; const y = -x; console.log(x == x + 1); // true console.log(y == y - 1); // true
However, comparisons of integers greater than Number.MAX_SAFE_INTEGER may produce unexpected results.
Key Takeaway
For accurate representation and comparison of large integers, use BigInt. For smaller integers, the Number type is sufficient, but be aware of the maximum safe integer value for bitwise operations.
The above is the detailed content of What's the Highest Integer JavaScript Can Represent Without Losing Precision?. For more information, please follow other related articles on the PHP Chinese website!