Glossary / Number precision

Number precision

JavaScript’s Number type is IEEE 754 binary64 floating point. It has a wide range but finite precision: every integer is exactly represented only up to Number.MAX_SAFE_INTEGER (2^53 - 1) and down to its negative. Above that, distinct integers can round to the same Number, silently corrupting identifiers or counters.

Safe integers and precision

Number.MAX_SAFE_INTEGER; // 9007199254740991
9007199254740992 === 9007199254740993; // true after Number rounding
Number.isSafeInteger(9007199254740993); // false

Use Number.isSafeInteger when exact integer identity matters. For larger integer domains, preserve values as strings or use BigInt, subject to API and database support. JSON has a number grammar that can contain long digit sequences, but JSON.parse converts them to Number and may lose precision before application code sees them.

For floating results, equality with === is often inappropriate; choose a tolerance based on scale and domain. Number.EPSILON is spacing near 1, not a universal threshold. Financial calculations usually need integer minor units or a decimal arithmetic library, with explicit rounding policy. Do not convert to fixed decimals and back expecting the underlying binary value to become exact.

Interview questions

  1. What is the safe integer limit? 2^53 - 1 in magnitude.
  2. Why can JSON integer IDs be corrupted? Parsing into Number loses distinctions beyond safe precision.
  3. Is Number.EPSILON a general comparison tolerance? No; tolerance depends on value scale and the problem.
  4. How represent large exact IDs? As strings or BigInt with a compatible wire contract.

References