Lesson 3 · 3 of 20
Numbers and Math · JavaScript
Do maths in JavaScript: operators, the remainder with %, powers, rounding with toFixed and the functions of the Math object, with practical examples.

In JavaScript all numbers are of type number, with or without decimals. The basic operators are +, -, * and /. The room's area is width * length; Math.round() rounds it to the nearest whole number and `toFixed(2)` writes it with two decimals (as text).
Division with / always gives the exact result: 27 / 12 is 2.25. To know how many boxes of 12 eggs get filled, use `Math.floor()`, which rounds down, and for the eggs left over, the remainder %: 27 % 12 is 3.
** raises to a power and Math.sqrt() gives the square root. Math.max() and Math.min() return the largest and smallest of the numbers they receive, and `Math.ceil()` rounds up: 130 people on 55-seat buses need 3 buses.
Decimals are stored in binary and some are not exact: 0.1 + 0.2 gives 0.30000000000000004. To show money or measurements, round them with toFixed().
Number() turns text into a number and parseInt() reads the whole number at the start of a text, like "15 kg". If the text is not a number, the result is `NaN` (Not a Number).
Code · main.js
// Whole numbers and decimals are all of type "number".const width = 4.5; // metresconst length = 3.2;const area = width * length;console.log("Area:", area, "m2");console.log("Rounded:", Math.round(area), "| Two decimals:", area.toFixed(2));// Division, whole part and remainderconst eggs = 27;console.log("27 / 12 =", eggs / 12);console.log("Full boxes of 12:", Math.floor(eggs / 12));console.log("Eggs left over:", eggs % 12);// Powers and rootsconsole.log("2 to the 10th:", 2 ** 10, "| Square root of 144:", Math.sqrt(144));// Highest, lowest, rounding upconsole.log("Warmest day:", Math.max(14, 19, 23, 17, 9));console.log("Coldest day:", Math.min(14, 19, 23, 17, 9));console.log("Buses for 130 people (55 seats):", Math.ceil(130 / 55));// Decimals are not always exact in binary:console.log(0.1 + 0.2, "->", (0.1 + 0.2).toFixed(2));// From text to numberconsole.log(Number("42") + 8, "| parseInt:", parseInt("15 kg"), "| Not a number:", Number("abc"));Output · node main.js
Area: 14.4 m2 Rounded: 14 | Two decimals: 14.40 27 / 12 = 2.25 Full boxes of 12: 2 Eggs left over: 3 2 to the 10th: 1024 | Square root of 144: 12 Warmest day: 23 Coldest day: 9 Buses for 130 people (55 seats): 3 0.30000000000000004 -> 0.30 50 | parseInt: 15 | Not a number: NaN
Key points
%is the remainder of a division.Math.floorrounds down,Math.ceilup andMath.roundto the nearest.toFixed(n)gives a string withndecimals.- Decimals are not always exact: round them when you show them.
Number("abc")givesNaN.
Exercise
Work out how many boxes of 6 bottles you need for 50 bottles and how many go in the last box, and the price of 7 bottles at 1.35 euros with two decimals.