The Math object has a number of intrinsic properties and methods. The properties are specific numbers.
Using the Math Object
One of these specific numbers is the value of pi (approximately 3.14159...). This is the value of the Math.PI property, which is used in the following example.
В | Copy Code |
---|---|
// A radius variable is declared and assigned a numeric value. var radius = 4; var area = Math.PI * radius * radius; // Note capitalization of Math and PI. |
One built-in method of the Math object is the exponentiation method, or pow, which raises a number to a specified power. The following example uses both pi and exponentiation.
В | Copy Code |
---|---|
// This formula calculates the volume of a sphere with the given radius. var volume = (4/3)*(Math.PI*Math.pow(radius,3)); |
Another example is as follows:
В | Copy Code |
---|---|
var x = Math.floor( Math.random()*10 ) + 1; |
The Math object cannot be explicitly constructed; it is always available to the program.