The math object is another object you’ll find yourself using often. It allows you to perform advance math operations. It can really save you time and you don’t have to write as much code.
Math Object Properties
Let’s get started. Clear your script and add this bit of code.
document.write( Math.PI + '<br>' );
You do not have to create an instance of the math object. You can use the math object directly with the Math keyword. The math object has a couple of properties, but we’ll only focus on 1. The PI property simply returns the value of PI. The real power of the math object is the methods it contains.
Math Object Methods
Add this bit of code into your script.
document.write( Math.ceil( 4.1 )+ '<br>' );
document.write( Math.floor( 4.9 ) + '<br>' );
document.write( Math.round( 4.45 ) + '<br>' );
document.write( Math.pow( 5, 2 ) + '<br>' );
document.write( Math.random() + '<br>' );
document.write( Math.sqrt( 25 ) + '<br>' )
There are a couple of methods to go over. You should get something close to this.
Here is what each method does
- ceil() – This method will round any number to the nearest integer. An integer is a number without a decimal. It is important to know that this method will round up no matter what. So, a number like 4.1 will always be rounded up to 5.
- floor() – This method is similar to the ceil() method except it rounds down no matter what. So, a number like 4.9 will always be rounded to 4.
- round() – This method will round a number to the nearest integer. Unlike the floor() and ceil() methods, this method will round the number up or down depending on the decimal values. A number like 4.5 will round to 5.
- pow(x, y) – This method will return the value of x to the power of y. x being the value in the first parameter and y being the value in the second parameter.
- random() – This method will return a completely random number from 0 to 1.
- sqrt( x ) – This method will return the square root of x. x being the value passed in the first parameter.
We’ll be using these methods in future tutorials when we start building real world applications
The math object has plenty of properties and methods to use. If you’re unsure on how to do a certain math operation, consider looking into the math object to do what you’re looking for. Here’s a link for more information about the math object. It also includes a list of all properties and methods related to the math object.