Constants
Math.PI
→ 3.141592653589793
Math.E
→ 2.718281828459045
Math.LN2
→ 0.6931471805599453
(Natural log of 2
)
Math.SQRT2
→ 1.4142135623730951
(Square root of 2
)
Rounding & Truncation
Math.floor(x)
→ Rounds down to the nearest integer.
Math.ceil(x)
→ Rounds up to the nearest integer.
Math.round(x)
→ Rounds to the nearest integer (>= 0.5
rounds up).
Math.trunc(x)
→ Removes the decimal part (no rounding).
console.log(Math.floor(4.9)); // 4
console.log(Math.ceil(4.1)); // 5
console.log(Math.round(4.5)); // 5
console.log(Math.trunc(-4.9)); // -4
Random Number Generation
Math.random()
→ Returns a random decimal between 0
and 1
(excluding 1
).
- Get a random integer in range
[min, max]
:
function getRandomInt(min: number, max: number) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
console.log(getRandomInt(1, 10)); // e.g. 7
Min & Max
Math.max(...values)
→ Returns the largest value.
Math.min(...values)
→ Returns the smallest value.
let numbers = [3, 7, 2, 9, 5];
console.log(Math.max(...numbers)); // 9
console.log(Math.min(...numbers)); // 2
Power & Roots