Numbers

Updated · 8 min read
easyES2026javascriptnumbersfloating-pointnaninterview

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, -3 and 1e6 are all the same type, number.
  • Decimals are stored in binary, so most can't be exact: 0.1 + 0.2 is 0.30000000000000004.
  • For money, store whole cents (12050 for $120.50) and format only for display.
  • NaN ("not a number") results from invalid math; test it with Number.isNaN. Infinity results from overflow or dividing by zero.
  • Integers are exact only up to Number.MAX_SAFE_INTEGER (about 9 quadrillion). Beyond that, use BigInt.

Writing Numbers

literals.js▶ Try it
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);
Output
120
45.5
-3
1000000
2500
0.0003
255 10 15
FormExampleValue
Decimal120, 45.5120, 45.5
Numeric separators1_000_0001000000 (the _ is only for readability)
Exponent2.5e3, 3e-42500, 0.0003
Hexadecimal0xff255
Binary0b101010
Octal0o1715

One Type for Everything

one-type.js▶ Try it
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));
Output
number number
true
3.5
true false

120 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

float.js▶ Try it
console.log(0.1 + 0.2);
console.log(0.1 + 0.2 === 0.3);
console.log(1.15 * 100);
console.log(19.99 * 3);
Output
0.30000000000000004
false
114.99999999999999
59.97

Computers 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:

epsilon.js▶ Try it
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);
Output
true
2.220446049250313e-16

Number.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

cents.js▶ Try it
const pricesInCents = [1999, 1999, 1999];
const totalCents = pricesInCents.reduce((sum, p) => sum + p, 0);
 
console.log(totalCents);
console.log(`$${(totalCents / 100).toFixed(2)}`);
Output
5997
$59.97

Integer 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:

nan.js▶ Try it
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"));
Output
NaN
NaN
NaN
number
NaN
false
true
true false

Explanation: 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:

infinity.js▶ Try it
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));
Output
Infinity -Infinity
Infinity
NaN
true false false

Number.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:

safe.js▶ Try it
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);
Output
9007199254740991
true
true
false
9007199254740992

Explanation: 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:

total.js▶ Try it
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)}`);
Output
Skipping invalid amount "abc"
Total: $65.29

Math.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:

FactCause
0.1 isn't exact1/10 has an infinitely repeating binary expansion, cut off at 53 bits
Integers exact to 2⁵³ − 153 bits of precision
MAX_VALUE ≈ 1.8 × 10³⁰⁸The largest 11-bit exponent
-0 existsThe sign bit is separate from the value
NaN and InfinityReserved 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
add-money.js▶ Try it
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));
Output
0.3
20
3.45

Quick check: Numbers

3 questions
1What is typeof NaN?
2What is the best way to store $120.50 for exact arithmetic?
3Which check is false for NaN, Infinity and non-numbers alike?

Key Takeaways

CheckUse
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?

Lesson 23 of 139