In JavaScript, the Number type is a double-precision 64-bit binary format IEEE 754 value. Unlike many other programming languages, JavaScript does not have separate types for integers (like int or long) and floating-point numbers (like float or double). Everything is a Number, though the introduction of BigInt has recently provided a way to handle arbitrarily large integers.
1. The IEEE 754 Standard (Double Precision)
Every number in JavaScript is stored as a 64-bit floating-point value. This bit-level architecture is divided into three parts:
- Sign bit (1 bit): Determines if the number is positive or negative.
- Exponent (11 bits): Determines the magnitude.
- Fraction/Mantissa (52 bits): Determines the precision.
The Floating-Point “Precision Bug”
Because numbers are stored in binary, certain decimal fractions (like $0.1$ or $0.2$) cannot be represented exactly. This leads to the famous rounding error:
console.log(0.1 + 0.2); // 0.30000000000000004
console.log(0.1 + 0.2 === 0.3); // false
Solution: When dealing with currency or critical precision, use Math.round() or a library like decimal.js, or convert the values to integers (cents instead of dollars) before calculating.
2. Integer Range and Precision
While all numbers are floats, JavaScript can represent integers perfectly up to a certain limit.
- Safe Integer Range: The maximum integer that can be represented without losing precision is $2^{53} – 1$.
Constants: * Number.MAX_SAFE_INTEGER ($9,007,199,254,740,991$)
Number.MIN_SAFE_INTEGER($-9,007,199,254,740,991$)
If you exceed these limits, calculations become unreliable:
console.log(Number.MAX_SAFE_INTEGER + 1); // 9007199254740992
console.log(Number.MAX_SAFE_INTEGER + 2); // 9007199254740992 (Oops!)
3. Special Numeric Values
JavaScript defines several symbolic values that represent non-standard numeric states:
NaN(Not-a-Number): Occurs when a mathematical operation fails (e.g.,0 / 0or"abc" * 10).- Self-Comparison:
NaNis the only value in JS that does not equal itself (NaN === NaNisfalse). UseNumber.isNaN()to check for it. Infinity&-Infinity: Occurs when a number exceeds the overflow limit (e.g.,1 / 0).-0(Negative Zero): A byproduct of the sign-bit logic. Useful in certain geometric/physical calculations to indicate direction.
4. Number Methods and Formatting
The Number prototype provides several essential methods for controlling how numbers appear and behave.
A. Formatting for Humans
toFixed(digits): Formats a number with a fixed number of decimals. Returns a string.
(2.456).toFixed(2); // "2.46"
toPrecision(digits): Formats a number to a total number of significant digits.toLocaleString(): Formats numbers according to local currency/language rules.
(1234567.89).toLocaleString('de-DE'); // "1.234.567,89"
B. Parsing and Validation
Number.parseInt()/Number.parseFloat(): Converts strings to numbers. It stops at the first non-numeric character.Number.isFinite(): Determines if a value is a finite number (notInfinityorNaN).
