Math Object
The JavaScript Math Object might not be used quite as often as the string object, but it is really useful when dealing with numbers. Sometimes we need to find the nearest integer to a number with a decimal (float). Other times, we need to do some sophisticated mathematics on them, such as powers or square roots. The math object is also where random number generation resides.
Number in JavaScript are really simple and so is the Math Object. However, I have sort of mislead you on numbers and the Math Object. See, the Math Object acts upon numbers, they do not utilize the Math Object as a method. As you will see in the examples below, we must perform the Math methods on our numbers. This is why you will see Math.method(number) being used in the references below. I know it seems like once you have a number it should have methods that do these Math Object Methods, but they simply don't exist.
Common Math Object Methods
abs(x)
– gets absolute value of x
document.write(Math.abs(-1));
ceil(x)
– gets x rounded up to the nearest integer
document.write(Math.ceil(2.6));
floor(x)
– gets x rounded down to the nearest integer
document.write(Math.floor(2.6));
max(x,y,z,…)
– gets the highest number of the arguments
document.write(Math.max(2,3,4,5));
min(x,y,z,…)
– gets the lowest number of the arguments
document.write(Math.min(2,3,4,5));
pow(x,y)
– gets x to the power of y
document.write(Math.pow(2,3));
random()
– generates random number between 0 and 1
document.write(Math.random());
round(x)
– gets x rounded to the nearest integer
document.write(Math.round(2.5));
sqrt(x)
– gets the square root of x
document.write(Math.sqrt(16));