Summary - Numbers and Math
Build a dice roll simulation using Math methods.
Summary - Numbers and Math
In this group you met JavaScript's single number type, number; integers and decimals live in the same type.
The Math object gives rounding and randomness: Math.round goes to the nearest, Math.floor down, Math.ceil up; Math.random produces a random 0-1 value; Math.min and Math.max pick the smallest and largest.
To convert to a number you use parseInt (with radix 10), parseFloat and Number. Edge cases show as NaN and Infinity; you test both safely with Number.isNaN and Number.isFinite.
Exercise Parse two prices, round, find the larger
Assign parseFloat("19.49") to priceA and parseFloat("25.99") to priceB. Put Math.round(priceA) and Math.round(priceB) into rA and rB. Then put Math.max(rA, rB) into larger and log larger with console.log.
Show example solution
const priceA = parseFloat("19.49");
const priceB = parseFloat("25.99");
const rA = Math.round(priceA);
const rB = Math.round(priceB);
const larger = Math.max(rA, rB);
console.log(larger);
Exercise Roll two dice, find the smaller
Assign Math.floor(Math.random() * 6) + 1 to roll1 and roll2. Then use Math.min to put the smaller roll into smaller and log smaller with console.log.
Show example solution
const roll1 = Math.floor(Math.random() * 6) + 1;
const roll2 = Math.floor(Math.random() * 6) + 1;
const smaller = Math.min(roll1, roll2);
console.log(smaller);
Test yourself
-
Match each method to its job
- Math.round
- Nearest whole number
- Math.floor
- Down to whole number
- parseInt
- Parses string to integer
- Math.random
- Random 0 to 1 value
-
What does parseInt("100", 2) return?
console.log(parseInt("100", 2));- 100
- 4
- 2
- NaN
Show answer
4 — Correct. Radix 2 means binary; "100" in binary equals 4.