Math Object & Number Methods
The Math object provides mathematical constants and functions — rounding, random numbers, min/max, powers, and more. Number methods handle parsing, formatting, and validation.
Math & Numbers
- Math.round() — Round to nearest integer: Math.round(4.5) = 5
- Math.floor() / Math.ceil() — Round down/up: floor(4.9) = 4, ceil(4.1) = 5
- Math.random() — Random 0–1 (exclusive). Random int: Math.floor(Math.random() * max)
- Math.max() / Math.min() — Find largest/smallest: Math.max(1, 5, 3) = 5
- Math.abs() — Absolute value: Math.abs(-5) = 5
- Number.isInteger() / Number.isFinite() / Number.isNaN() — Type checks
- parseFloat() / parseInt() — Parse strings to numbers: parseInt('42px') = 42
- toFixed(n) — Format decimal places: (3.14159).toFixed(2) = '3.14' (returns string!)
Math & Number Code
// Rounding
console.log(Math.round(4.5)); // 5
console.log(Math.round(4.4)); // 4
console.log(Math.floor(4.9)); // 4 (always down)
console.log(Math.ceil(4.1)); // 5 (always up)
console.log(Math.trunc(4.9)); // 4 (remove decimals)
// Random numbers
console.log(Math.random()); // 0.0 to 0.999...
// Random integer between min and max (inclusive)
function randomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
console.log(randomInt(1, 10)); // 1 to 10
console.log(randomInt(1, 100)); // 1 to 100
// Math functions
console.log(Math.max(3, 7, 2, 9, 1)); // 9
console.log(Math.min(3, 7, 2, 9, 1)); // 1
console.log(Math.abs(-42)); // 42
console.log(Math.pow(2, 10)); // 1024
console.log(Math.sqrt(144)); // 12
console.log(Math.PI); // 3.14159...
// Number methods
console.log(Number.isInteger(42)); // true
console.log(Number.isFinite(Infinity)); // false
console.log(Number.isNaN(NaN)); // true
console.log(parseInt("42px")); // 42
console.log(parseFloat("3.14em")); // 3.14
console.log((99.956).toFixed(2)); // "99.96"Tip
Tip
Use Math.round, Math.floor, and Math.ceil intentionally. floor always rounds down, ceil always rounds up, round rounds to nearest. For currency, use (Math.round(price * 100) / 100).toFixed(2) to avoid floating-point errors.
undefined/functions dropped. Always try/catch parse.
Common Mistake
Warning
Math.random() is NOT cryptographically secure. Never use it for passwords, tokens, or security-sensitive randomness. Use crypto.getRandomValues() or crypto.randomUUID() for secure random values.
Practice Task
Note
Math utilities: (1) Generate a random hex color. (2) Build a dice roller (1-6 random). (3) Create a function that clamps a number between a min and max value. (4) Calculate distance between two points.
Quick Quiz
Key Takeaways
- The Math object provides mathematical constants and functions — rounding, random numbers, min/max, powers, and more.
- Math.round() — Round to nearest integer: Math.round(4.5) = 5
- Math.floor() / Math.ceil() — Round down/up: floor(4.9) = 4, ceil(4.1) = 5
- Math.random() — Random 0–1 (exclusive). Random int: Math.floor(Math.random() * max)