Numbers
Numbers are everywhere: prices in a cart, a user's age, the number of likes. JavaScript has one type for all of them — number — and whole and fractional values are stored the same way.
Whole and fractional numbers
Whole numbers are written as usual, and the fractional part is separated with a dot:
console.log(3.5 + 1); // 4.5Long numbers can be split with underscores — JavaScript simply ignores them, and the code becomes easier to read:
const population = 1_500_000;
console.log(population); // 1500000Rounding
For rounding there is the built-in Math object — a set of mathematical functions. Functions that belong to an object are called methods and are called with a dot:
console.log(Math.round(4.6)); // 5| Method | What it does | 4.6 | 4.2 |
|---|---|---|---|
Math.round() | to the nearest whole number | 5 | 4 |
Math.floor() | always down | 4 | 4 |
Math.ceil() | always up | 5 | 5 |
Math.trunc() | drops the fractional part | 4 | 4 |
Decimal places
The toFixed() method keeps the given number of digits after the dot. Note that it returns a string, not a number — handy for showing prices:
const price = 19.987;
console.log(price.toFixed(2)); // 19.99If you need to keep calculating with the result, turn the string back into a number with Number().
Maximum, minimum and roots
The Math object can find the largest and smallest of several numbers and take a square root:
console.log(Math.max(3, 9, 4)); // 9
console.log(Math.min(3, 9, 4)); // 3
console.log(Math.sqrt(16)); // 4Another useful method is Math.random(): it returns a random fraction between 0 and 1 and comes in handy in games and tests.
Infinity and NaN
Dividing by zero in JavaScript does not cause an error; it gives the special value Infinity. And when a calculation makes no sense, the result is NaN (Not a Number):
console.log(10 / 0); // Infinity
console.log('abc' * 2); // NaNYou can check a result for NaN with Number.isNaN(): it returns true when the calculation failed.
Common mistake
Fractional numbers are stored approximately, so simple addition sometimes produces "extra" digits:
console.log(0.1 + 0.2); // 0.30000000000000004
console.log(0.1 + 0.2 === 0.3); // falseThis is a feature of almost every programming language, not a JavaScript bug. Round the result with toFixed() for display, and count money in cents — as whole numbers.