JavaScript's Numeric Limits: Precision and Scale
JavaScript's ability to represent numeric values has limits. Understanding these boundaries is crucial to prevent inaccuracies or unexpected behavior in applications.
Number Type
JavaScript has two numeric types: Number and BigInt. The Number type, represented by a 64-bit floating-point IEEE 754 number, is commonly used for arithmetic operations.
Maximum Safe Integer
The largest integer value that a Number can represent without losing precision is Number.MAX_SAFE_INTEGER, which equates to:
BigInt
For handling extremely large integer values, JavaScript offers the BigInt type. Unlike Number, BigInt has no pre-defined upper bound.
Bitwise and Shift Operators
It's important to note that bitwise and shift operators operate on 32-bit integers. As such, the maximum safe integer for these operators is 231-1 or 2,147,483,647.
Example
The following JavaScript code demonstrates the limitations of JavaScript's Number type:
const x = 9007199254740992; const y = -x; console.log(x == x + 1); // true console.log(y == y - 1); // also true // Arithmetic operators work, but bitwise/shifts only operate on int32: console.log(x / 2); // 4503599627370496 console.log(x >> 1); // 0 console.log(x | 1); // 1
The above is the detailed content of What are the Limits of JavaScript's Number Type and How Does BigInt Address Them?. For more information, please follow other related articles on the PHP Chinese website!