9.5 The Math Object
The Math object allows you to work with more advanced arithmetic calculations, such as square root, trigonometric functions, logarithms, and random numbers , than are provided by the basic numeric operators. If you are doing simple calculations, you really won't need it.
Unlike other objects, you don't have to create an instance of the Math object with the new keyword. It is a built-in object and has a number of properties (see Table 9.5) and methods (see Table 9.6). The Math object always starts with an uppercase M.
Table 9.5. Math object properties.
Table 9.6. Math object methods.
Square Root, Power of, and Pi
The Math object comes with a number of common mathematical constants (all uppercase), such as PI and natural log values, as well as methods to find the square root of a number, the power of a number, and so on. Example 9.16 demonstrates how to use some of these properties; the output is shown in Figure 9.17.
Figure 9.17. Output from Example 9.16.
9.5.1 Rounding Up and Rounding Down
The ceil() Method
The ceil() method rounds a number up to the next largest whole number and then removes any numbers after the decimal point; thus, 5.02 becomes 6 because 6 is the next largest number, and “5.02 becomes “5 because “5 is larger than “6.
The floor() Method
The floor() method rounds a number down to the next lowest whole number and then removes any numbers after the decimal point; thus, 5.02 now becomes 5, and “5.02 becomes “6.
The round() Method
The round() method rounds up only if the decimal part of the number is .5 or greater. Otherwise, it rounds down to the nearest integer; thus, 5.5 is rounded up to 6, and 5.4 is rounded down to 5.
Table 9.7. Rounding up and down.
Figure 9.18. Output from Example 9.17.
9.5.2 Generating Random Numbers
The Math object's random() method returns a random fractional number between 0 and 1 and is seeded with the computer's system time. (The seed is the starting number for the algorithm that produces the random number.) The Math object's floor() method truncates numbers after the decimal point and returns an integer.