Skip to content
BigInt and Numeric Edge Cases
step 1/7

Reading — step 1 of 7

Learn

~3 min readNumbers and Performance

JavaScript's Number is IEEE-754 double-precision float — for ANY numeric value, including integers. This causes precision issues familiar to every JS developer. BigInt (ES2020) is the escape hatch.

The integer problem

Doubles can EXACTLY represent integers up to 2^53. Beyond that, integer math is broken:

javascript

Common bites: large IDs from databases, financial values in cents, timestamps in microseconds.

BigInt — arbitrary precision

javascript

BigInts work with + - * / % ** but only with other BigInts:

javascript

Division truncates (integer division):

javascript

Comparisons and equality:

javascript

Limitations:

  • No Math methods (Math.sqrt(4n) throws)
  • Can't be JSON.stringifyd directly (throws). Convert to string first.
  • Slower than Number for typical sizes — only use when you need >53-bit precision

Other numeric quirks

Floating-point precision:

javascript

Canonical workaround for finite decimals: scale to integers and divide at the end (or use a library like decimal.js for arbitrary precision decimals).

NaN and Infinity:

javascript

NaN is the only value not equal to itself. Always use Number.isNaN() instead of ===.

Negative zero:

javascript

Bitwise operators on Numbers silently truncate to 32-bit signed integers:

javascript

If you need 64-bit integer ops, BigInt has bitwise operators that don't overflow.

When to reach for BigInt

  • IDs from databases (Postgres bigserial, Twitter snowflake)
  • Cryptography (RSA, ECC)
  • Financial values where every cent matters and you want integer arithmetic
  • Algorithms that exceed 2^53

For everyday counters, sizes, percentages — Number is faster and sufficient.

Common mistakes

  • Mixing Number and BigInt without explicit conversion — TypeError.
  • JSON.stringify on BigInt — crashes. Convert to string before serializing.
  • Trusting === between BigInt and Number — always false even for same value.
  • Using Number for IDs >2^53 — silently corrupts. Use BigInt or string.
  • Comparing floats with === — floating point makes this unreliable. Use Math.abs(a - b) < ε.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…