JavaScript Numbers and Math

JavaScript numbers use a single type, number, for both integers and decimals. It is a 64-bit floating point value. For huge whole numbers there is also bigint. The built-in Math object provides rounding, powers, random numbers and more.

Floating Point Precision

Some decimals cannot be stored exactly in binary, so tiny rounding errors appear. Round for display, or work in whole units (like cents) for money.

console.log(0.1 + 0.2);
console.log((0.1 + 0.2).toFixed(2));
console.log(Number((0.1 + 0.2).toFixed(2)) === 0.3);
0.30000000000000004
0.30
true

Converting Strings to Numbers

Number() needs the entire string to be numeric. parseInt and parseFloat read as much as they can from the start. NaN ("Not a Number") signals a failed conversion; test for it with Number.isNaN().

console.log(Number("42"), Number("42px"));
console.log(parseInt("42px", 10), parseFloat("3.75kg"));
console.log(Number.isNaN(Number("abc")));
console.log(Number.isInteger(5.0), Number.isInteger(5.5));
42 NaN
42 3.75
true
true false

The Math Object

console.log(Math.round(4.5), Math.floor(4.9), Math.ceil(4.1), Math.trunc(-4.7));
console.log(Math.max(3, 9, 2), Math.min(3, 9, 2));
console.log(Math.sqrt(81), Math.abs(-12), Math.PI.toFixed(4));
5 4 5 -4
9 2
9 12 3.1416

Random Numbers

Math.random() returns a decimal from 0 (inclusive) to 1 (exclusive). Multiply and floor it to get a random integer in a range.

function randomInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}
console.log("Dice roll:", randomInt(1, 6));
Dice roll: 4   (varies each run)

Formatting and BigInt

toLocaleString and Intl.NumberFormat format numbers for humans. Numbers are only precise up to Number.MAX_SAFE_INTEGER; beyond that use BigInt by adding n.

console.log((1234567.891).toLocaleString("en-US"));
console.log(new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" }).format(49.9));
console.log(Number.MAX_SAFE_INTEGER);
console.log(2n ** 64n);
1,234,567.891
$49.90
9007199254740991
18446744073709551616

Frequently asked questions

Why does 0.1 + 0.2 not equal 0.3 in JavaScript?

Numbers are stored in binary floating point, which cannot represent 0.1 exactly. The tiny error shows up in the sum. Round results or compare with a small tolerance.

How do I round to 2 decimal places in JavaScript?

Use num.toFixed(2) for a display string, or Math.round(num * 100) / 100 for a number.

How do I generate a random integer between two numbers?

Use Math.floor(Math.random() * (max - min + 1)) + min, which includes both min and max.