Numbers & Math
JavaScript uses a single number type for whole numbers and decimals alike. That keeps things simple, but it also explains a few famous surprises, like 0.1 + 0.2 not quite equalling 0.3. This page covers number quirks, conversion, rounding and the built-in Math object.
One number type
42, -7 and 3.14 are all of type number. Behind the scenes every number is stored as a 64-bit floating-point value. Whole numbers are exact up to Number.MAX_SAFE_INTEGER, which is 9007199254740991 (about 9 quadrillion). Beyond that, use BigInt by adding n to the end: 9007199254740993n. You can write large numbers with underscores for readability: 1_500_000 is one and a half million.
Floating-point surprises
Computers store numbers in binary, and many simple decimals, such as 0.1, have no exact binary form, just as 1/3 has no exact decimal form. The tiny errors usually stay hidden but sometimes show up:
console.log(0.1 + 0.2); console.log(0.1 + 0.2 === 0.3); console.log((0.1 + 0.2).toFixed(2));
This is not a JavaScript bug; Python, Java and C behave the same. Two practical habits avoid trouble. When displaying, round with toFixed(). When handling money, work in whole cents and only divide by 100 to display:
const priceCents = 1999; // KES 19.99 const qty = 3; const totalCents = priceCents * qty; console.log(totalCents / 100);
Never compare decimal results with ===. Instead check that the difference is tiny, for example Math.abs(a - b) < 0.000001, or compare rounded values.
NaN and Infinity
When a calculation can't produce a meaningful number, JavaScript returns a special value instead of crashing:
console.log(10 / 0);
console.log(-10 / 0);
console.log("abc" * 2);
console.log(typeof NaN);
console.log(NaN === NaN);
console.log(Number.isNaN("abc" * 2));
NaN means "Not a Number", yet its type is number. It also spreads: any arithmetic with NaN gives NaN, so one bad input can poison a whole calculation. Because NaN is never equal to itself, the only reliable test is Number.isNaN(value).
Converting strings to numbers
console.log(Number("42"));
console.log(Number("42px"));
console.log(parseInt("42px"));
console.log(parseFloat("3.5kg"));
console.log(Number(""));
console.log(Number(" 12 "));
Number() is strict: the whole string (ignoring surrounding spaces) must be a number, or you get NaN. parseInt() and parseFloat() read as many digits as they can from the start and ignore the rest. Watch out for Number(""), which is 0, not NaN; check for empty input separately. The unary plus +"5" also converts to a number and works like Number().
Rounding and formatting
const price = 249.567; console.log(Math.round(price)); console.log(Math.floor(price)); console.log(Math.ceil(price)); console.log(Math.trunc(-4.7)); console.log(price.toFixed(2)); console.log(Math.round(price * 100) / 100);
Math.round()rounds to the nearest whole number (halves go up:Math.round(2.5)is 3).Math.floor()always rounds down andMath.ceil()always rounds up.Math.trunc()chops off the decimal part, so -4.7 becomes -4 (whileMath.floor(-4.7)is -5).toFixed(2)gives exactly two decimal places but returns a string, ready for display.
For thousands separators, use toLocaleString(): (1500000).toLocaleString("en-KE") gives "1,500,000".
The Math object
Math is a built-in object full of maths helpers:
console.log(Math.max(72, 95, 88)); console.log(Math.min(72, 95, 88)); console.log(Math.sqrt(144)); console.log(Math.abs(-30)); console.log(Math.PI);
To find the largest value in an array, spread it into Math.max: Math.max(...scores). You'll learn the spread syntax on the Arrays page.
Random numbers
Math.random() returns a decimal from 0 (included) up to but not including 1. To get a random whole number from min to max inclusive, scale it, round it down and shift it:
const roll = Math.floor(Math.random() * 6) + 1; // 1 to 6
console.log("You rolled", roll);
const min = 100;
const max = 999;
const code = Math.floor(Math.random() * (max - min + 1)) + min;
console.log("Your one-time code:", code);
Your numbers will differ every time you run it. Math.random() * 6 gives something between 0 and 5.999..., Math.floor turns that into 0 to 5, and adding 1 shifts it to 1 to 6.
Math.random() is fine for games and quizzes but is not secure. For passwords, tokens or anything security-related, browsers provide crypto.getRandomValues().
Key points
- All numbers share one type; decimals can carry tiny binary rounding errors, so round for display and use cents for money.
NaNresults from failed maths; test it withNumber.isNaN().- Convert text with
Number()(strict) orparseInt()/parseFloat()(lenient). - Round with
Math.round,floor,ceil,truncortoFixed(which returns a string). Math.floor(Math.random() * n) + 1gives a random whole number from 1 to n.
Tip: use the ← and → keys to move between pages.
