Math Object
- The JavaScript Math Object allows you to perform mathematical tasks on numbers.
Printing PI value (3.14)
console.log(Math.PI); // 3.141592653589793
Math.round()
- Math.round(x) returns the value of x rounded to its nearest integer.
let num = 10.501;
console.log(Math.round(num)); // 11
Math.pow()
- Math.pow(x, y) returns the value of x to the power y.
console.og(Math.pow(2, 3)); // 8
console.og(2**3); // 8
Math.sqrt()
- Math.sqrt(x) returns the square root of x.
console.log(Math.sqrt(25)); // 5
console.log(Math.sqrt(81)); // 9
Math.abs()
- Math.abs(x) returns the absolute (positive) value of x.
console.log(Math.abs(-55)); // 55
console.log(Math.abs(-55.5)); // -55.5
Math.ceil()
- Math.ceil(x) returns the value of x rounded up to its nearest integer.
console.log(Math.ceil(4.51)); // 5
console.log(Math.round(4.51)); // 5
console.log(Math.ceil(99.01)); // 100
console.log(Math.round(99.1)); // 99
Math.floor()
- Math.floor(x) returns the value of x rounded down to its nearest integer.
console.log(Math.floor(99.01)); // 99
console.log(Math.floor(99.1)); // 99
Math.min()
- Math.min() can be used to find the lowest value in a list of arguments.
console.log(Math.min(0, 150, 30, 20, -8, -200)); // -200
Math.max()
- Math.max() can be used to find the highest value in a list of arguments
console.log(Math.max(0, 150, 30, 20, -8, -200)); // 150
Math.trunc()
- The trunc() method returns the integer part of a number.
console.log(Math.trunc(4.6)); // 4
console.log(Math.trunc(-99.1)); // -99
Practise time ⌣
- If the argument is a positive number, Math.trunc() is equivalent to Math.floor(), otherwise Math.trunc() is equivalent to Math.ceil().