|
Free Open Book
Sams Teach Yourself JavaScript in 24 Hours |
Using the Math ObjectThe Math object is a built-in JavaScript object that includes math constants and functions. You don't need to create a Math object; it exists automatically in any JavaScript program. The Math object's properties represent mathematical constants, and its methods are mathematical functions. Rounding and TruncatingThree of the most useful methods of the Math object enable you to round decimal values up and down:
All of these take the number to be rounded as their single parameter. You might notice one thing missing: the capability to round to a decimal place, such as for dollar amounts. Fortunately, you can easily simulate this. Here is a simple function that rounds numbers to two decimal places: function round(num) {
return Math.round(num * 100) / 100;
}
This function multiplies the value by 100 to move the decimal, and then rounds the number to the nearest integer. Finally, the value is divided by 100 to restore the decimal to its original position. Generating Random NumbersOne of the most commonly used methods of the Math object is the Math.random() method, which generates a random number. This method doesn't require any parameters. The number it returns is a random decimal number between zero and one. You'll usually want a random number between one and a value. You can do this with a general-purpose random number function. The following is a function that generates random numbers between one and the parameter you send it: function rand(num) {
return Math.floor(Math.random() * num) + 1;
}
This function multiplies a random number by the value specified in the num parameter, and then converts it to an integer between one and the number by using the Math.floor() method. Other Math FunctionsThe Math object includes many functions beyond those you've looked at here. For example, Math.sin() and Math.cos() calculate sines and cosines. The Math object also includes properties for various mathematical constants, such as Math.PI. See Appendix D, "JavaScript Quick Reference," for a complete list of math functions and constants. |
Main Menu |
| 500 Juegos Gratis | 500 Giochi Gratis | 500 Jeux Gratuits | 500 Jogos Gratis | 500 Kostenlose Spiele |