Learn JavaScript · lesson 7 of 60 · about 7 minutes
Numbers and the Math Object
Give Sam's posts a reading time: round numbers with Math, find remainders with %, and show decimals neatly with toFixed.
What you'll learn
- Use % and **
- Round with Math.round, floor and ceil
- Format numbers with toFixed()
A reading time
Sam wants each post to show *Reading time: 2 min*. People read about 200 words a minute, and the newest post has 350 words. Dividing gives 1.75, and *1.75 min* looks odd. You need a whole number.
Division gives the exact answer, decimals and all
console.log(350 / 200);Output
1.75The Math object
Math is built into JavaScript and full of number tools: Math.round (to the nearest whole number), Math.floor (always down), Math.ceil (always up), Math.max, Math.min and Math.abs.
For a reading time, round up: a 1.75-minute read takes 2 minutes.
Three ways to round 1.75
console.log(Math.round(1.75), Math.floor(1.75), Math.ceil(1.75));
console.log(Math.ceil(400 / 200));
console.log(Math.max(4, 9, 2), Math.min(4, 9, 2));Output
2 1 2
2
9 2Two more operators
%gives the remainder after dividing:7 % 3is 1**raises to a power:2 ** 3is 8
A number is even when n % 2 is 0.
135 seconds in minutes and seconds
const seconds = 135;
console.log(Math.floor(seconds / 60), seconds % 60);
console.log(2 ** 10);Output
2 15
1024Decimals aren't always exact, so tidy them before showing them
console.log(0.1 + 0.2);
const rating = 4.666;
console.log(rating.toFixed(1));Output
0.30000000000000004
4.7Tip
Computers store decimals in binary, so 0.1 + 0.2 isn't exactly 0.3. toFixed() rounds to the number of decimal places you ask for and gives back text, ready to show.
Now try it yourself
This lesson is free in Codiqo, with 10 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.