Numbers & Math
Round numbers, generate random ones, and use the built-in Math toolbox.
What you will learn
- Convert and round numbers
- Generate random numbers
- Use the Math object
The Math object
| Expression | Result |
|---|---|
Math.round(4.6) | 5 |
Math.floor(4.9) | 4 (round down) |
Math.ceil(4.1) | 5 (round up) |
Math.max(3, 9, 5) | 9 |
Math.min(3, 9, 5) | 3 |
Math.random() | A random decimal 0–1 |
A classic use of Math is making a random dice roll. Let us build one and unpack the formula.
<script>
// Random whole number from 1 to 6 (a dice roll)
let dice = Math.floor(Math.random() * 6) + 1;
document.write("You rolled a " + dice);
</script>Work from the inside out: Math.random() gives a decimal like 0.74; * 6 stretches it to somewhere between 0 and 5.99; Math.floor(...) chops off the decimals to a whole 0–5; and + 1 shifts that to the 1–6 we want. Reload and the number changes each time.
Note: Output: You rolled a 4 (Your number will vary — it is random. It is always a whole number from 1 to 6.)
Strings to numbers
Form inputs arrive as strings. Convert them with Number(), parseInt() or parseFloat() before doing maths.
<script>
let input = "42"; // a string
let n = Number(input); // now a number
document.write(n + 8); // 50, not "428"
</script>input is the text "42" (note the quotes). Number(input) converts it into the real number 42 and stores it in n. Now n + 8 adds to make 50. Without the conversion, "42" + 8 would have joined into the text "428" — a very common form-handling bug.
Note: Output: 50
Q. How do you get a random whole number from 0 to 9?
✍️ Practice
- Generate and print a random number between 1 and 100.
- Round 3.14159 down, up, and to the nearest whole number.
🏠 Homework
- Build a “guess the dice” demo that rolls a random 1–6 each time you reload.