Sub topic 5
Inside the Number Type: NaN, -0, Infinity, and Precision
This chapter assumes you know the seven primitive types and can run JavaScript in a browser console or Node.js. Most later results in this tutorial, such as NaN == NaN being false or Number("abc") producing NaN, follow from how the Number type works. This chapter explains that model.
The Working Model: IEEE 754 Doubles
Every JavaScript number is a 64-bit floating-point value in the IEEE 754 "double precision" format. JavaScript has no separate integer type for number. The literal 42 and the literal 42.0 are the same value.
The 64 bits are split into three fields:
| Field | Bits | Purpose |
|---|---|---|
| Sign | 1 | 0 for positive, 1 for negative |
| Exponent | 11 | Scales the value by a power of two |
| Fraction (mantissa) | 52 | The significant digits, plus one implied leading bit, for 53 bits of precision |
Each edge case in this chapter comes from this layout:
- Binary fractions cannot represent most decimal fractions exactly, so arithmetic rounds.
- Only 53 bits of precision exist, so large integers lose exactness.
- The sign bit is separate from the rest of the value, so zero can be positive or negative.
- Special exponent values are reserved for
InfinityandNaN.
Floating-Point Rounding
The decimal 0.1 is a repeating fraction in binary, much as 1/3 is in decimal. JavaScript stores the nearest double it can, and adding two rounded values gives a rounded result:
console.log(0.1 + 0.2); // 0.30000000000000004
console.log(0.1 + 0.2 === 0.3); // false
console.log((1.005).toFixed(2)); // "1.00": 1.005 is stored as 1.00499999...
console.log(Number.EPSILON); // 2.220446049250313e-16The usual mistake is comparing computed decimals with ===. Compare them against a tolerance instead. A tolerance that scales with the size of the operands works across magnitudes:
function nearlyEqual(a, b, relTol = Number.EPSILON * 4) {
if (a === b) return true; // handles Infinity and exact matches
const diff = Math.abs(a - b);
const scale = Math.max(Math.abs(a), Math.abs(b));
return diff <= scale * relTol;
}
console.log(nearlyEqual(0.1 + 0.2, 0.3)); // true
console.log(nearlyEqual(1e20 + 1e4, 1e20)); // true: 1e4 is below 1e20's precision
console.log(nearlyEqual(1, 1.001)); // falseNaN: The Value That Is Not Equal to Itself
NaN ("Not a Number") is the result of a numeric operation that has no meaningful answer. Its type is still "number".
console.log(typeof NaN); // "number"
console.log(0 / 0); // NaN
console.log(Math.sqrt(-1)); // NaN
console.log(Infinity - Infinity); // NaN
console.log(Number("abc")); // NaN
console.log(undefined + 1); // NaN
console.log(NaN + 5); // NaN: NaN spreads through arithmetic
console.log(NaN === NaN); // falseIEEE 754 defines NaN as unequal to everything, including itself. As a result, x === NaN is always false and can never detect it. You have three working options:
const x = Number("abc");
console.log(Number.isNaN(x)); // true: checks for NaN, no conversion
console.log(Object.is(x, NaN)); // true: SameValue treats NaN as equal to NaN
console.log(x !== x); // true: only NaN is unequal to itself
// The global isNaN converts its argument to a number first:
console.log(isNaN("abc")); // true: "abc" becomes NaN
console.log(Number.isNaN("abc")); // false: "abc" is a string, not NaN
console.log(isNaN("")); // false: "" becomes 0Because NaN spreads through arithmetic, a single bad input can turn a whole calculation into NaN with no error thrown. Validate inputs where they enter your code, not at the end of the calculation.
Negative Zero
Since the sign bit is independent, IEEE 754 has both +0 and -0. Most operations hide the difference:
const negZero = 0 * -1;
console.log(negZero === 0); // true
console.log(String(negZero)); // "0"
console.log(JSON.stringify(negZero)); // "0"
console.log(`${negZero}`); // "0"
// Places where -0 shows itself:
console.log(1 / negZero); // -Infinity
console.log(Object.is(negZero, 0)); // false
console.log(Math.sign(negZero)); // -0
console.log(Math.round(-0.4)); // -0
console.log(negZero.toLocaleString()); // "-0" in current engines-0 shows up from rounding small negative values, from multiplying zero by a negative number, and from operations such as -x when x is 0. It matters when the sign carries meaning. Examples include a velocity that reached zero while moving left, or a direction derived from Math.atan2, where Math.atan2(0, -0) is π but Math.atan2(0, 0) is 0. To detect it, use Object.is(value, -0).
Infinity
A result too large to represent becomes Infinity or -Infinity. It is a real value that compares and calculates consistently:
console.log(1 / 0); // Infinity
console.log(-1 / 0); // -Infinity
console.log(Number.MAX_VALUE); // 1.7976931348623157e+308
console.log(Number.MAX_VALUE * 2); // Infinity: overflow
console.log(Infinity > Number.MAX_VALUE); // true
console.log(Infinity - Infinity); // NaN
console.log(Infinity * 0); // NaN
console.log(Number.isFinite(Infinity)); // false
console.log(Number.isFinite("5")); // false: no conversion
console.log(isFinite("5")); // true: global version convertsDivision by zero does not throw in JavaScript. If a value must be an ordinary usable number, Number.isFinite is the single check that rejects NaN, Infinity, -Infinity, and non-numbers at once.
The Safe Integer Limit
With 53 bits of precision, a double holds every integer exactly only up to 2^53 − 1. Beyond that, adjacent integers share a representation:
console.log(Number.MAX_SAFE_INTEGER); // 9007199254740991
console.log(2 ** 53 === 2 ** 53 + 1); // true: precision is lost
console.log(9007199254740993); // 9007199254740992
console.log(Number.isSafeInteger(2 ** 53 - 1)); // true
console.log(Number.isSafeInteger(2 ** 53)); // false
console.log(Number.isInteger(2 ** 53)); // true, but not safe"Safe" means the integer and its neighbors are all represented exactly, so n + 1 really is the next integer. The bug usually shows up when parsing external data such as 64-bit database IDs or tweet IDs from JSON. JSON.parse silently rounds them. Keep such IDs as strings, or use BigInt, which the next chapter covers.
Choosing the Right Check
| Question | Use | Avoid |
|---|---|---|
| Is it NaN? | `Number.isNaN(x)` | `x === NaN`, global `isNaN` |
| Is it a usable finite number? | `Number.isFinite(x)` | global `isFinite` |
| Is it an exact integer? | `Number.isSafeInteger(x)` | `Number.isInteger` alone |
| Is it negative zero? | `Object.is(x, -0)` | `x === -0` |
| Are two computed decimals equal? | Tolerance comparison | `===` |
Exercise
Predict the output of each line: (a) [0.1 + 0.2 === 0.3, Object.is(0.1 + 0.2, 0.3)], (b) Number.isNaN("hello"), (c) 1 / Math.round(-0.2), (d) Number.isSafeInteger(2 ** 53 + 2).
Show answer
(a) [false, false], because the sum is 0.30000000000000004 and neither comparison method changes that. (b) false, because Number.isNaN does not convert and a string is not NaN. (c) -Infinity, because Math.round(-0.2) is -0 and dividing 1 by -0 gives -Infinity. (d) false, because the value is above Number.MAX_SAFE_INTEGER.
Exercise
Write a function toPositiveQuantity(input) that takes user input (a string or number) and returns a safe positive integer, or null if the input is invalid. It must reject "", "abc", "Infinity", "2.5", "-3", and "9007199254740993".
Show answer
One correct version is: function toPositiveQuantity(input) { if (typeof input === "string" && input.trim() === "") return null; const n = Number(input); return Number.isSafeInteger(n) && n > 0 ? n : null; }. The empty-string check is needed because Number("") is 0, although n > 0 would also reject it. Number.isSafeInteger rejects NaN, Infinity, fractions, and values above 2^53 − 1. It also rejects "9007199254740993", which parses to 9007199254740992 and is therefore not safe.