Syntax
Math.round(num)
Math.floor(num)
Math.max(...nums)Examples
Rounding Methods
The different ways to round a number, and how they differ.
console.log(Math.round(4.5)); // 5 - rounds to nearest, ties round up
console.log(Math.round(4.4)); // 4
console.log(Math.floor(4.9)); // 4 - always rounds down
console.log(Math.ceil(4.1)); // 5 - always rounds up
console.log(Math.trunc(4.9)); // 4 - simply removes the decimal part
console.log(Math.trunc(-4.9)); // -4 - different from floor for negativesabs(), max(), and min()
Absolute value and finding extremes among values.
console.log(Math.abs(-5)); // 5
console.log(Math.max(3, 7, 2)); // 7
console.log(Math.min(3, 7, 2)); // 2
// Finding max/min in an array requires spread
const numbers = [4, 8, 2, 9, 1];
console.log(Math.max(...numbers)); // 9pow() and sqrt()
Power and square root operations.
console.log(Math.pow(2, 3)); // 8 - same as 2 ** 3
console.log(2 ** 3); // 8 - the ** operator is now preferred
console.log(Math.sqrt(16)); // 4
console.log(Math.cbrt(27)); // 3 - cube rootBest practices
- Use the ** exponentiation operator instead of Math.pow() in modern code - it is more concise for the common case
- Choose the right rounding method deliberately - round() for nearest, floor()/ceil() when you specifically need to always round down/up
- Use Math.max(...array) with spread syntax to find the largest value in an array, since Math.max() itself takes individual arguments
- Remember Math methods are all static - always call them as Math.round(), never new Math().round()
Runtime & versions
Browsers and JavaScript runtimes. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
ECMAScript specification