Numbers
A number in JavaScript is a value used for counting and calculating. Unlike Java or C, JavaScript has a single number type for whole numbers and decimals alike: every number is a 64-bit floating-point value following the IEEE 754 standard. That one design choice explains the language's most famous surprise (0.1 + 0.2 isn't exactly 0.3), the special values NaN and Infinity, and why the Fee Tracker stores money in cents.
In One Minute
120,45.5,-3and1e6are all the same type,number.- Decimals are stored in binary, so most can't be exact:
0.1 + 0.2is0.30000000000000004. - For money, store whole cents (
12050for $120.50) and format only for display. NaN("not a number") results from invalid math; test it withNumber.isNaN.Infinityresults from overflow or dividing by zero.- Integers are exact only up to
Number.MAX_SAFE_INTEGER(about 9 quadrillion). Beyond that, useBigInt.
Writing Numbers
console.log(120);
console.log(45.5);
console.log(-3);
console.log(1_000_000);
console.log(2.5e3);
console.log(3e-4);
console.log(0xff, 0b1010, 0o17);120
45.5
-3
1000000
2500
0.0003
255 10 15| Form | Example | Value |
|---|---|---|
| Decimal | 120, 45.5 | 120, 45.5 |
| Numeric separators | 1_000_000 | 1000000 (the _ is only for readability) |
| Exponent | 2.5e3, 3e-4 | 2500, 0.0003 |
| Hexadecimal | 0xff | 255 |
| Binary | 0b1010 | 10 |
| Octal | 0o17 | 15 |
One Type for Everything
console.log(typeof 120, typeof 45.5);
console.log(120 === 120.0);
console.log(7 / 2);
console.log(Number.isInteger(120), Number.isInteger(45.5));number number
true
3.5
true false120 and 120.0 are the same value. Division always gives the exact (floating-point) result, never a truncated integer. Number.isInteger tells you whether a number has a fractional part.
Why 0.1 + 0.2 Isn't 0.3
console.log(0.1 + 0.2);
console.log(0.1 + 0.2 === 0.3);
console.log(1.15 * 100);
console.log(19.99 * 3);0.30000000000000004
false
114.99999999999999
59.97Computers store numbers in binary (base 2). Just as 1/3 can't be written exactly in decimal (0.3333...), most decimal fractions, including 0.1 and 0.2, can't be written exactly in binary. Each is stored as the nearest possible binary value, and the tiny errors show up after arithmetic. This isn't a JavaScript bug: Java's double, Python's float and Excel behave the same way, because they all use IEEE 754.
Comparing Decimals Safely
When you do need to compare floating-point results, check whether they are close enough, using a small tolerance called epsilon:
function nearlyEqual(a, b, epsilon = 1e-9) {
return Math.abs(a - b) < epsilon;
}
console.log(nearlyEqual(0.1 + 0.2, 0.3));
console.log(Number.EPSILON);true
2.220446049250313e-16Number.EPSILON is the gap between 1 and the next representable number. It is a useful tolerance for values near 1; for larger values, scale the tolerance with the numbers.
Money in Cents
const pricesInCents = [1999, 1999, 1999];
const totalCents = pricesInCents.reduce((sum, p) => sum + p, 0);
console.log(totalCents);
console.log(`$${(totalCents / 100).toFixed(2)}`);5997
$59.97Integer arithmetic is exact (up to 9 quadrillion), so totals in cents never drift. toFixed(2) formats with two decimals; the next lesson covers formatting, including Intl.NumberFormat for "$1,234.50".
NaN: Not a Number
NaN is a special number value meaning "the result of a calculation that has no numeric answer". It appears when converting text that isn't a number, or doing invalid math:
console.log(Number("abc"));
console.log(0 / 0);
console.log("fee" * 2);
console.log(typeof NaN);
console.log(NaN + 5);
console.log(NaN === NaN);
console.log(Number.isNaN(Number("abc")));
console.log(isNaN("abc"), Number.isNaN("abc"));NaN
NaN
NaN
number
NaN
false
true
true falseExplanation: typeof NaN is "number": it is a number value that represents a failed calculation. It spreads (any math with NaN gives NaN), and it isn't equal to anything, even itself. Test for it with Number.isNaN(x). The older global isNaN converts its argument first, so isNaN("abc") is true even though "abc" is a string, not NaN. Use Number.isNaN.
Infinity
Infinity and -Infinity represent values beyond the largest number, or division by zero:
console.log(1 / 0, -1 / 0);
console.log(Number.MAX_VALUE * 2);
console.log(Infinity - Infinity);
console.log(Number.isFinite(120), Number.isFinite(Infinity), Number.isFinite(NaN));Infinity -Infinity
Infinity
NaN
true false falseNumber.isFinite(x) is the quickest way to check that a value is a real, usable number: it is false for NaN, Infinity and -Infinity, and for non-numbers.
Safe Integers
A 64-bit float has 53 bits for the digits, so integers are exact only up to 2⁵³ − 1:
console.log(Number.MAX_SAFE_INTEGER);
console.log(Number.MAX_SAFE_INTEGER + 1 === Number.MAX_SAFE_INTEGER + 2);
console.log(Number.isSafeInteger(9007199254740991));
console.log(Number.isSafeInteger(9007199254740992));
console.log(9007199254740993);9007199254740991
true
true
false
9007199254740992Explanation: above the safe limit, consecutive integers can't all be represented, so two different numbers compare equal, and 9007199254740993 is stored as ...992. This matters for large IDs from databases (often 64-bit integers): treat them as strings, or use BigInt (next-but-one lesson).
In Practice
The Fee Tracker totals a list of payment amounts typed as dollars. It converts each to integer cents once, at the edge, rejects anything invalid, and sums exactly:
function toCents(input) {
const dollars = Number(input);
if (!Number.isFinite(dollars) || dollars < 0) return null;
return Math.round(dollars * 100);
}
const typed = ["19.99", "0.10", "0.20", "abc", "45"];
let totalCents = 0;
for (const value of typed) {
const cents = toCents(value);
if (cents === null) {
console.log(`Skipping invalid amount "${value}"`);
continue;
}
totalCents += cents;
}
console.log(`Total: $${(totalCents / 100).toFixed(2)}`);Skipping invalid amount "abc"
Total: $65.29Math.round(dollars * 100) fixes the tiny binary errors at conversion time (1.15 * 100 would otherwise be 114.99999999999999).
Common Mistakes
Comparing decimals with ===. Use integers (cents) or a tolerance.
Testing for NaN with === or the global isNaN. Use Number.isNaN.
Storing large IDs as numbers. IDs above 2⁵³ − 1 lose digits. Keep them as strings.
Summing values that might be NaN. One bad value poisons the total. Validate with Number.isFinite first.
Under the Hood
An IEEE 754 double uses 64 bits: 1 sign bit, 11 exponent bits and 52 fraction bits (plus an implied leading 1, giving 53 bits of precision). The value is roughly sign × 1.fraction × 2^exponent, which is scientific notation in base 2. That layout explains everything above:
| Fact | Cause |
|---|---|
0.1 isn't exact | 1/10 has an infinitely repeating binary expansion, cut off at 53 bits |
| Integers exact to 2⁵³ − 1 | 53 bits of precision |
MAX_VALUE ≈ 1.8 × 10³⁰⁸ | The largest 11-bit exponent |
-0 exists | The sign bit is separate from the value |
NaN and Infinity | Reserved exponent patterns |
Engines optimize behind the scenes: V8 stores small integers (called Smis) in a compact tagged form and does integer arithmetic on them when it can, switching to full doubles only when needed. The language still behaves as if every number were a double.
Interview Corner
Why is 0.1 + 0.2 !== 0.3 in JavaScript?
Numbers are IEEE 754 binary64 floats. 0.1 and 0.2 have no finite binary representation, so each is rounded to the nearest double; their sum rounds to 0.30000000000000004, which is a different double from the one nearest 0.3. Compare with a tolerance, or use integers (such as cents) for exact decimal arithmetic.
What is NaN, and how do you check for it?
NaN is a number value representing an undefined or unrepresentable result, such as 0/0 or Number("abc"). It is the only value not equal to itself. Check with Number.isNaN(x) (no coercion) or Object.is(x, NaN); the global isNaN coerces its argument first.
What is Number.MAX_SAFE_INTEGER?
2⁵³ − 1 = 9,007,199,254,740,991, the largest integer n such that n and n + 1 are both exactly representable. Beyond it, integer arithmetic loses precision; use BigInt.
Practice
Challenge: Write addMoney(a, b) that adds two dollar amounts given as numbers and returns the exact result rounded to cents, so that addMoney(0.1, 0.2) returns 0.3.
Show solution
function addMoney(a, b) {
const cents = Math.round(a * 100) + Math.round(b * 100);
return cents / 100;
}
console.log(addMoney(0.1, 0.2));
console.log(addMoney(19.99, 0.01));
console.log(addMoney(1.15, 2.3));0.3
20
3.45Key Takeaways
| Check | Use |
|---|---|
Is it NaN? | Number.isNaN(x) |
| Is it a usable number? | Number.isFinite(x) |
| Is it a whole number? | Number.isInteger(x) |
| Is the integer exact? | Number.isSafeInteger(x) |
| Close enough? | Math.abs(a - b) < 1e-9 |
Was this tutorial helpful?