Numbers and math
Overview
JavaScript has one main number type for both whole numbers and decimals. Under the hood every number is a 64-bit “double-precision floating point” value — the same format most languages use for decimals.
const items = 3;
const price = 4.99;
console.log(items * price); // 14.97Numbers can be written in several ways:
1000000; // ordinary
1_000_000; // underscores for readability — same value
2.5e6; // scientific notation: 2,500,000
0.000_001; // also fine
0xff; // hexadecimal: 255
0b1010; // binary: 10Arithmetic operators
10 + 3; // 13
10 - 3; // 7
10 * 3; // 30
10 / 3; // 3.3333333333333335
10 % 3; // 1 (remainder)
2 ** 3; // 8 (exponent)The usual maths order applies: ** first, then *, / and %, then + and -. Use parentheses to make your intent obvious:
2 + 3 * 4; // 14
(2 + 3) * 4; // 20The remainder operator
% gives what’s left over after division. It’s surprisingly useful:
7 % 2 === 1; // odd number check
10 % 5 === 0; // divisible by 5
(index + 1) % 3; // cycle 1, 2, 0, 1, 2, 0 …Updating a number
let count = 10;
count += 5; // 15 (same as count = count + 5)
count -= 2; // 13
count *= 2; // 26
count /= 2; // 13
count++; // 14 (add one)
count--; // 13 (subtract one)The Math object
Math is a built-in object full of maths helpers and constants.
Math.round(4.6); // 5
Math.floor(4.6); // 4
Math.ceil(4.1); // 5
Math.trunc(-4.6); // -4
Math.max(3, 9, 2); // 9
Math.min(3, 9, 2); // 2
Math.abs(-7); // 7
Math.sqrt(16); // 4
Math.PI; // 3.141592653589793
Math.random(); // a number from 0 up to (not including) 1Four ways to round
The four rounding functions only disagree when numbers have a fractional part — and especially when they’re negative:
Math.flooralways moves down (towards −∞).Math.ceilalways moves up (towards +∞).Math.truncsimply chops off the decimal part (towards 0).Math.roundgoes to the nearest whole number; exactly.5goes up.
Random numbers
Math.random() returns a decimal from 0 up to (but not including) 1. Scale and floor it to get whole numbers in a range. A random whole number from 1 to 6:
const roll = Math.floor(Math.random() * 6) + 1;Step by step: Math.random() * 6 gives 0 to 5.999…; Math.floor turns that into 0–5; + 1 shifts it to 1–6. Picking a random item from an array uses the same idea:
const colours = ['red', 'green', 'blue'];
const pick = colours[Math.floor(Math.random() * colours.length)];Not for passwords or tokens.
Math.random()is predictable enough for games but not for security. Usecrypto.getRandomValues()orcrypto.randomUUID()instead.
Decimal surprises
Numbers are stored in binary, so some decimals — like 0.1 — can’t be represented exactly, in the same way 1/3 can’t be written exactly in decimal (0.333…). Tiny errors appear:
0.1 + 0.2; // 0.30000000000000004
0.1 + 0.2 === 0.3; // false
(0.1 + 0.2).toFixed(2); // '0.30'To compare decimals, check that they’re close enough rather than exactly equal:
Math.abs((0.1 + 0.2) - 0.3) < Number.EPSILON; // trueWorking with money? Store amounts in the smallest unit (cents or paise) as whole numbers, and divide only when you display them.
1999cents is always exact;19.99might not be.
Formatting numbers
(4.5).toFixed(2); // '4.50' — fixed decimal places (returns a string)
(1234.5678).toFixed(1); // '1234.6'
(0.000123).toPrecision(2); // '0.00012'
(1234567.891).toLocaleString('en-IN'); // '12,34,567.891'
(1234567.891).toLocaleString('en-US'); // '1,234,567.891'For currencies, Intl.NumberFormat handles symbols and separators for any locale:
const rupees = new Intl.NumberFormat('en-IN', { style: 'currency', currency: 'INR' });
rupees.format(1499.5); // '₹1,499.50'Converting text to numbers
Values from forms and URLs arrive as strings. Convert them before doing maths:
Number('42'); // 42
Number('42px'); // NaN — the whole string must be a number
Number(''); // 0 — careful!
parseInt('42px'); // 42 — reads digits until it hits something else
parseFloat('3.5kg'); // 3.5
+'7'; // 7 — unary plus, a common shorthandparseInt should be given a base (radix) when the input could be ambiguous: parseInt('08', 10).
Special values
NaN (“not a number”) appears when maths fails, such as Number('abc') or 0 / 0. Any maths involving NaN also gives NaN, and NaN is the only value that isn’t equal to itself — so check for it with Number.isNaN(value).
Number.isNaN(Number('abc')); // true
NaN === NaN; // false!
Number.isInteger(5.0); // true
Number.isInteger(5.5); // false
1 / 0; // Infinity
-1 / 0; // -Infinity
Number.isFinite(1 / 0); // falseSafe integers
Whole numbers are exact up to Number.MAX_SAFE_INTEGER (about 9 quadrillion). Beyond that, numbers start skipping values. Use BigInt (123n) when you need exact arithmetic on bigger whole numbers.
Round a price
Write formatPrice(n) that returns the number rounded to 2 decimal places as a string, e.g. formatPrice(4.5) → '4.50'. Then write randomBetween(min, max) that returns a random whole number from min to max, inclusive.
function formatPrice(n) {
// your code here
}
function randomBetween(min, max) {
// your code here
}function formatPrice(n) {
return n.toFixed(2);
}
function randomBetween(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}Summary
- All JavaScript numbers are 64-bit floating point; use
BigIntfor huge whole numbers. %gives the remainder and**raises to a power;++/--add or subtract one.Mathholds helpers likeMath.round,Math.floor,Math.maxandMath.random.- Decimals can be slightly off — round when you display them, and store money in whole cents.
- Convert text with
Number()and check for failure withNumber.isNaN().