Numbers and the Math Object
7 min read
Numbers
JavaScript has a single number type that represents both integers and floating-point numbers as 64-bit IEEE 754 doubles. This means integers up to 2^53 − 1 are exact; beyond that, use BigInt.
javascript
console.log(0.1 + 0.2); // 0.30000000000000004
console.log(Number.isFinite(1/0)); // false (Infinity)
console.log(Number.isNaN(0/0)); // true
console.log(Number.isInteger(3.0)); // true
// Parsing
Number.parseInt("42px"); // 42
Number.parseFloat("3.14em"); // 3.14
Number("42"); // 42
Number(""); // 0
Number("abc"); // NaNThe Math Object
javascript
Math.round(4.6); // 5
Math.floor(4.9); // 4
Math.ceil(4.1); // 5
Math.abs(-7); // 7
Math.max(1, 5, 3); // 5
Math.min(1, 5, 3); // 1
Math.pow(2, 10); // 1024
Math.sqrt(144); // 12
Math.trunc(-4.7); // -4
Math.random(); // [0, 1)
// Random integer in [min, max]
const rand = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;For financial calculations, avoid floating-point arithmetic altogether. Work in the smallest currency unit (cents) as integers, or use a decimal library. 0.1 + 0.2 !== 0.3 is a real bug in money code.
Ready to test yourself?
Practice JavaScript— quiz & coding exercises