Sub topic 1
One Number Type: How JavaScript Stores Numbers
Many languages give you separate types for integers and fractions, such as int, long, float, and double. JavaScript's everyday arithmetic uses a single type, Number, for all of these. Integers like 42 and fractions like 0.75 are stored in the same 64-bit format and follow the same rules. This chapter explains that format. Many surprises in the later chapters come from it, including rounding errors, NaN, -0, and the limit on exact integers.
Prerequisites
This chapter assumes you can:
- Read and write basic JavaScript: variables, functions, and operators.
- Run code in a browser console or in Node.js.
- Use strict equality (
===) and thetypeofoperator.
You don't need to know binary arithmetic in advance. The chapter explains the parts of it that you need.
One Type for Integers and Fractions
In JavaScript, 42 and 42.0 are the same value. Nothing records whether you wrote a decimal point.
console.log(typeof 42); // "number"
console.log(typeof 4.2); // "number"
console.log(42 === 42.0); // true
console.log(Number.isInteger(5.0)); // true
console.log(7 / 2); // 3.5 (no integer division)The last line trips up developers who come from C, Java, or Python 2. Dividing two whole numbers does not truncate, because no integer type exists to truncate into. To get an integer result you round on purpose, for example with Math.trunc(7 / 2). A later chapter covers rounding.
JavaScript has one other numeric primitive, BigInt, which holds integers of any size. You write it with an n suffix (10n). BigInt is a separate type with its own rules, and the final chapter covers it. In the rest of this chapter, "number" means the Number type.
IEEE 754 Double Precision
A Number is a 64-bit floating-point value in the IEEE 754 "double precision" format. This is the same format as double in C and Java and float in Python. The 64 bits are split into three fields.
| Field | Bits | Purpose |
|---|---|---|
| Sign | 1 | 0 for positive, 1 for negative |
| Exponent | 11 | Power of two, stored with a bias of 1023 |
| Fraction (mantissa) | 52 | The digits after the leading binary 1 |
For ordinary ("normal") numbers, the stored value is:
value = (-1)^sign × 1.fraction (in binary) × 2^(exponent − 1023)The leading 1. is not stored. Every normal number has one, so the format leaves it out and gets an extra bit of precision for free. The total precision is therefore 53 significant binary digits, which is roughly 15 to 17 decimal digits.
The two reserved exponent patterns explain where the special values come from. An exponent field of all zeros encodes 0, -0, and very small "subnormal" numbers. An exponent field of all ones encodes Infinity, -Infinity, and NaN. These values are part of the number format, not errors bolted on afterwards. The chapter on special values explains how to handle them.
Seeing the Bits Yourself
You can read the raw bits of any number with a DataView over an 8-byte buffer. The following function prints the three fields separated by spaces.
function bitsOf(x) {
const view = new DataView(new ArrayBuffer(8));
view.setFloat64(0, x); // big-endian by default
const high = view.getUint32(0).toString(2).padStart(32, "0");
const low = view.getUint32(4).toString(2).padStart(32, "0");
const all = high + low;
return `${all[0]} ${all.slice(1, 12)} ${all.slice(12)}`;
}
console.log(bitsOf(1));
// 0 01111111111 0000000000000000000000000000000000000000000000000000
console.log(bitsOf(-2));
// 1 10000000000 0000000000000000000000000000000000000000000000000000
console.log(bitsOf(0.5));
// 0 01111111110 0000000000000000000000000000000000000000000000000000
console.log(bitsOf(0.1));
// 0 01111111011 1001100110011001100110011001100110011001100110011010Here is how to read the output:
- For
1, the exponent field01111111111equals 1023, and 1023 − 1023 = 0. The fraction is all zeros, so the value is 1.0 × 2⁰ = 1. - For
-2, the sign bit is 1. The exponent is 1024, which gives 2¹. The value is −1.0 × 2 = −2. - For
0.5, the exponent is 1022, so the value is 1.0 × 2⁻¹ = 0.5. - For
0.1, the fraction is a repeating pattern1001 1001 ...that has been cut off and rounded at bit 52.
The 0.1 result is the key point. One tenth has no finite representation in binary, just as one third has no finite representation in decimal. JavaScript stores the closest double it can, and that value is very slightly larger than 0.1. Numbers built only from powers of two (0.5, 0.25, 0.375) are stored exactly. Most decimal fractions are not. The chapter on floating-point precision builds on this to explain 0.1 + 0.2.
Limits Built Into the Format
The fixed field sizes set hard limits. JavaScript exposes the most important ones as constants on Number.
console.log(Number.MAX_VALUE); // 1.7976931348623157e+308
console.log(Number.MIN_VALUE); // 5e-324
console.log(Number.EPSILON); // 2.220446049250313e-16
console.log(Number.MAX_SAFE_INTEGER); // 9007199254740991
console.log(Number.MAX_VALUE * 2); // Infinity| Constant | Meaning | Comes from |
|---|---|---|
| `Number.MAX_VALUE` | Largest finite number | Largest exponent with a fraction of all ones |
| `Number.MIN_VALUE` | Smallest positive number (it is subnormal) | The lowest bit set, with an exponent field of all zeros |
| `Number.EPSILON` | Gap between 1 and the next larger number, equal to 2⁻⁵² | 52 fraction bits |
| `Number.MAX_SAFE_INTEGER` | Largest n such that n and n + 1 are both exact, equal to 2⁵³ − 1 | 53 bits of precision |
Results that grow past MAX_VALUE overflow to Infinity without throwing an error. Results too small to represent underflow to 0. JavaScript never raises an exception for numeric overflow, so your code has to check for these cases itself.
Primitives Versus Number Objects
A number literal is a primitive value. Calls like (5).toFixed(2) work because JavaScript wraps the primitive in a temporary Number object for the method call. You can also create such a wrapper yourself with new Number, but you almost never should.
const prim = 5;
const boxed = new Number(5);
console.log(typeof prim); // "number"
console.log(typeof boxed); // "object"
console.log(boxed === 5); // false (different types)
console.log(boxed == 5); // true (unwrapped by loose equality)
console.log(new Number(0) ? "truthy" : "falsy"); // "truthy"
console.log(typeof Number("5")); // "number" (no `new`: converts)The last line shows the useful form. Calling Number(value) without new returns a primitive and is a standard way to convert values. The conversion chapter covers it in detail.
Common Errors
- Expecting integer division.
7 / 2is3.5. UseMath.truncorMath.floorwhen you want a whole number. - Assuming decimals are exact.
0.1,0.2, and most prices are stored as approximations. Plan for that before you compare or accumulate them. - Treating
typeof x === "number"as proof of a usable value.NaNandInfinityalso have type"number". - Using
new Number. The wrapper is an object, compares unequal to primitives with===, and is always truthy, even when it wraps0. - Reading
Number.MIN_VALUEas the lower bound. It is the tiny positive value closest to zero.
Exercise
Using the layout of sign, exponent (bias 1023), and fraction, what three bit fields does bitsOf(2) print, and why?
Show answer
It prints "0 10000000000" followed by 52 zeros. The sign is 0 because the number is positive. 2 = 1.0 × 2^1, so the stored exponent is 1 + 1023 = 1024, which is 10000000000 in binary. The fraction is all zeros because the leading 1 is implicit and nothing follows it.
Exercise
Why does bitsOf(0.375) end in a fraction field with only a few 1 bits followed by zeros, while bitsOf(0.1) shows a long repeating pattern?
Show answer
0.375 is 3/8, which is 0.011 in binary, so it equals 1.1 × 2^-2 and needs only one fraction bit. It is stored exactly. 0.1 has an infinitely repeating binary expansion (0.000110011...), so the 52-bit fraction holds a rounded, truncated copy of the pattern, and the stored value is only an approximation of 0.1.
Exercise
What do these lines print, and what one-line fix makes the condition behave as the author intended? const count = new Number(0); if (count) { console.log("has items"); }
Show answer
It prints "has items", because count is an object and every object is truthy, even one that wraps 0. Use a primitive instead: const count = 0; (or Number(0) without new). With that change the condition is falsy and nothing is printed.