Operators and strings · Lesson 9 of 45
Numbers and Math
Rounding, random numbers and formatting.
7 minutes3 games
The Math object holds ready-made number tools, and Number has helpers for converting and checking.
JavaScript
console.log(Math.round(4.5)) // 5 console.log(Math.floor(4.9)) // 4: down console.log(Math.ceil(4.1)) // 5: up console.log(Math.max(3, 9, 2)) // 9 console.log(Math.abs(-7)) // 7 console.log((19.9876).toFixed(2)) // "19.99" console.log(Number.isInteger(5.0)) // true
Random numbers
Math.random() returns a random number from 0 up to (not including) 1. For a whole number from 1 to 6 (a die):
JavaScript
const dice = Math.floor(Math.random() * 6) + 1
console.log("You rolled", dice)Run it a few times; you'll get different numbers.
Math.random() → 0 … 0.999
* 6 → 0 … 5.99
Math.floor → 0 … 5
+ 1 → 1 … 6
What's the output?
console.log(Math.floor(7.8)) console.log(Math.ceil(7.2))
What will this code print?
Quick question
What does (3.456).toFixed(1) return?
Exercise
Print the largest number using Math.max (42).
Expected output: 42
JavaScript
const scores = [12, 42, 7, 30]
Learn more from
Played 0 of 3 games
Sign in to save your progress and earn XP.