Home >Web Front-end >JS Tutorial >What are the Limits of JavaScript's Number Type and How Does BigInt Address Them?

What are the Limits of JavaScript's Number Type and How Does BigInt Address Them?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-20 15:35:10563browse

What are the Limits of JavaScript's Number Type and How Does BigInt Address Them?

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:

  • 253-1
  • /- 9,007,199,254,740,991
  • Nine quadrillion seven trillion one hundred ninety-nine billion two hundred fifty-four million seven hundred forty thousand nine hundred ninety-one

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn