In JavaScript, there is only one type for numbers: number. This single type is used to represent both integers (whole numbers like 10, -50) and floating-point numbers (decimals like 3.14, -0.5).
The Core Standard: All numbers in JavaScript are implemented as 64-bit double-precision floating-point numbers, following the international IEEE 754 standard. This is the same format used for double in languages like C++ and Java.
let integer = 100;
let float = 99.5;
console.log(typeof integer); // "number"
console.log(typeof float); // "number"
You can create numbers in several ways:
Standard Literals:
let a = 25; // Integer
let b = 12.34; // Floating-point
Exponential Notation (e): A shorthand for writing very large or very small numbers.
let billion = 1e9; // 1 followed by 9 zeros -> 1000000000
let tiny = 5e-6; // 5 / 10^6 -> 0.000005
Other Bases (Hex, Binary, Octal): You can also represent numbers in other numeral systems.
let hex = 0xFF; // Hexadecimal (base 16) -> 255 in decimal
let binary = 0b1010; // Binary (base 2) -> 10 in decimal
let octal = 0o77; // Octal (base 8) -> 63 in decimal
Because numbers are stored in a binary floating-point format (base-2), they cannot perfectly represent all decimal fractions (base-10). This leads to the most famous "gotcha" in JavaScript math.
console.log(0.1 + 0.2); // Outputs: 0.30000000000000004
console.log(0.1 + 0.2 === 0.3); // false
Why? The numbers 0.1 and 0.2 (and 0.3) have infinitely repeating representations in binary, similar to how 1/3 is 0.333... in decimal. The computer has to round them off to fit them into the 64-bit storage. These tiny rounding errors accumulate.
How to handle this:
.toFixed() method to round the result to a specific number of decimal places.