T
traeai
登录
返回首页
freeCodeCamp.org

JavaScript 安全整数限制

8.5Score
JavaScript 安全整数限制

TL;DR · AI 摘要

JavaScript 的安全整数限制是 9007199254740991。当计算超过这个限制时,JavaScript 开始进行近似计算。BigInt 是 JavaScript 引入的用于安全处理大整数的类型。

核心要点

  • JavaScript 的安全整数限制是 9007199254740991。
  • 当计算超过安全整数限制时,JavaScript 开始进行近似计算。
  • BigInt 是 JavaScript 引入的用于安全处理大整数的类型。

结构提纲

按章节快速跳转。

  1. JavaScript 是一种广泛使用的编程语言,但存在安全整数限制。

  2. 安全整数限制是 JavaScript 可以准确表示的最大整数。

  3. 当计算超过安全整数限制时,JavaScript 开始进行近似计算。

  4. BigInt 是 JavaScript 引入的用于安全处理大整数的类型。

思维导图

用一张图看清主题之间的关系。

查看大纲文本(无障碍 / 无 JS 友好)
  • JavaScript 安全整数限制
    • 安全整数限制
      • 定义
      • 示例
    • 精度错误
      • 原因
      • 示例
    • BigInt
      • 定义
      • 用途

金句 / Highlights

值得收藏与分享的关键句。

#JavaScript#Precision Error#BigInt
打开原文
Image 1: How to Understand the Safe Integer Limit in JavaScript

According to the Stack overflow technology survey in 2025, JavaScript is one of the most widely used programming languages in the world. We use it to build frontend applications, backend services, payment systems, analytics platforms, blockchain applications, and more.

But JavaScript has an interesting limitation that many developers don't fully understand until it causes a production issue. That limitation is called the safe integer limit.

In this article, you'll learn:

  • What the safe integer limit is
  • Why JavaScript has this limitation
  • How precision errors happen
  • What BigInt is
  • How modern systems use BigInt
  • How to use large integers safely in production applications

Table of Contents

Prerequisites

To follow along with this article, you should have:

  • Basic knowledge of JavaScript
  • A code editor or browser console
  • Familiarity with variables and functions

JavaScript uses the Number type to represent numbers.

For example:

code
const age = 25
const price = 99.99
const count = 1000

Under the hood, JavaScript stores numbers using the IEEE 754 double-precision floating-point format. You don't need to memorize the entire specification, but you should understand one important consequence: JavaScript can only represent integers accurately up to a certain point.

That point is:

code
console.log(Number.MAX_SAFE_INTEGER) // 9007199254740991

This is the largest integer JavaScript can safely represent using the Number type.

The smallest safe integer is:

code
console.log(Number.MIN_SAFE_INTEGER) // -9007199254740991

Why Is It Called a “Safe” Integer?

The word “safe” means JavaScript can still represent the integer accurately without losing precision. Once you go beyond the safe limit, JavaScript starts making approximation mistakes.

Let’s look at an example.

code
const max = Number.MAX_SAFE_INTEGER

console.log(max + 1) // 9007199254740992
console.log(max + 2) // 9007199254740992

This is incorrect because adding 1 and 2 shouldn't produce the same result, but guess what? This happens because JavaScript can no longer distinguish between nearby large integers accurately.

How Can You Understand This Problem if You Are New to the Game?

Imagine you have a camera. When you zoom in closely, you can see every small detail clearly. But when you zoom out too far, tiny details begin to disappear.

JavaScript numbers behave similarly. Small integers are represented precisely:

code
console.log(10)
console.log(100)
console.log(1000)

But extremely large integers lose detail because JavaScript runs out of precision. At that point, multiple numbers begin collapsing into the same value internally. That is why large integer calculations become unreliable.

How to Check if a Number Is Safe

JavaScript provides a built-in method called Number.isSafeInteger().

Example:

code
console.log(Number.isSafeInteger(100)) // true

Another example:

code
console.log(Number.isSafeInteger(Number.MAX_SAFE_INTEGER)) // true

But the below code returns false:

code
console.log(
  Number.isSafeInteger(Number.MAX_SAFE_INTEGER + 1)
) // false

This method is useful when validating large integers from APIs, databases, or user input.

Can Unsafe Integers Cause Any Problems?

Unsafe integers can create serious production bugs. For example, in financial calculations: imagine a payment platform processing extremely large transaction records. Precision issues can corrupt balances or reconciliation logic.

code
const amount = 9007199254740993

console.log(amount) // 9007199254740992

The value changes unexpectedly. That's dangerous for financial systems.

Another example is in analytics systems. Large-scale analytics platforms often track billions or trillions of events. Unsafe integers can distort counters and reports.

Also, distributed systems frequently generate very large IDs. Examples include database IDs, event IDs, transaction IDs, and blockchain transaction hashes. If precision is lost, systems may reference the wrong records.

Blockchain systems also commonly use extremely large integers. Ethereum, for example, stores values in wei. One Ether equals:

code
1,000,000,000,000,000,000 wei

That number exceeds JavaScript’s safe integer limit. Without proper handling, balances become inaccurate.

Introducing BigInt in JavaScript

JavaScript introduced BigInt to solve this problem. BigInt allows JavaScript to represent integers larger than the safe limit accurately. You can create a BigInt by adding n to the end of a number.

Example:

code
const largeNumber = 9007199254740993n

console.log(largeNumber) // 9007199254740993n

Notice that the value remains accurate. You can also create BigInt values using the BigInt() constructor.

code
const value = BigInt("9007199254740993123123123")

console.log(value)

How to Perform Operations with BigInt

You can use arithmetic operators with BigInt.

Here's an example:

code
const a = 1000000000000000000n
const b = 2n

console.log(a + b) // 1000000000000000002n
console.log(a - b) // 999999999999999998n
console.log(a * b) // 2000000000000000000n
console.log(a / b) // 500000000000000000n

How BigInt Differs from Number

One important rule is that you can't mix BigInt and Number directly.

This will throw an error:

code
const result = 1n + 1 // TypeError

You must convert explicitly, like this:

code
const result = 1n + BigInt(1)

console.log(result)

Or this:

code
const result = Number(1n) + 1

console.log(result)

Explicit conversion prevents accidental precision loss.

How Modern Software Uses BigInt

Many modern applications rely on BigInt. Let’s look at a practical example. Blockchain applications depend heavily on precise integer calculations.

Example:

code
const wei = 1000000000000000000n
const balance = 5000000000000000000n

console.log(balance / wei) // 5n

Libraries in Ethereum ecosystems often use BigInt internally for token balances and gas calculations.

When You Should Use BigInt

Use BigInt when:

  • Integer precision matters
  • Numbers exceed the safe limit
  • You're building blockchain applications
  • You're handling financial ledgers
  • You're processing massive counters
  • You're working with large database IDs

When You Should Not Use BigInt

Avoid BigInt when:

  • You need decimal calculations
  • You're building simple frontend interactions
  • Precision isn't critical
  • Performance matters more than huge integer support

BigInt operations are slower than normal Number operations because they require arbitrary-precision arithmetic.

Final Thoughts

JavaScript’s safe integer limit isn't just a theoretical concept. It affects real-world systems every day. As applications grow larger and more distributed, developers increasingly work with massive integers in payment systems, blockchain platforms, analytics pipelines, databases, event-driven architectures, and so on.

Understanding the safe integer limit helps you avoid subtle production bugs that are often difficult to detect. BigInt gives JavaScript the ability to handle these large integers safely and accurately. But like any powerful tool, it should be used intentionally.

Just keep in mind: Use normal Number values for everyday calculations. Use BigInt when precision becomes critical.

The key lesson is simple: large numbers aren't always safe numbers in JavaScript.

  • * *
  • * *

Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started

AI 可能会生成不准确的信息,请核实重要内容