| home / programming / java_core / 1 | [previous] |
|
|
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.
|
<head><title>The Math Object</title></head> <h2>Math object Methods--sqrt(),pow()<br> <script language="JavaScript"> document.write("<h3>The square root of " +num+ " is "); 2 document.write(Math.sqrt(num),".<br>"); document.write(".<br>"+num+" raised to the 3rd power is " ); 4 document.write(Math.pow(num,3)); |
There are three Math methods available for rounding numbers up or down. They are the ceil(), floor(), and round() methods (see Table 9.7 for examples). The differences between the methods might be confusing because all three methods truncate the numbers after the decimal point and return a whole number. If you recall, JavaScript also provides the parseInt() function, but this function truncates the number after the decimal point, without rounding either up or down.
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 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.
|
|
|---|
|
<head><title>The Math Object</title></head> <script language="JavaScript"> document.write("<I>The number being manipulated is: ", num, 2 document.write("The <I>Math.floor</I> method rounds down: " + 3 document.write("The <I>Math.ceil</I> method rounds up: " + 4 document.write("The <I>Math.round</I> method rounds to\ |
Random numbers are frequently used in JavaScript programs to produce random images (such as banners streaming across a screen), random messages, or random numbers (such as for lotteries or card games). There are examples throughout this text where random numbers are used.
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.
|
|
|---|
|
<html><head><title>Random Numbers</title> <script language="JavaScript"> // Generate random numbers between 0 and 10 |
The variable n is assigned an initial value of 10. This value will be the outside range of numbers randomly produced. |
| home / programming / java_core / 1 | [previous] |
| ||||||||||||||||||||
Created: March 11, 2003
Revised: November 19, 2003
URL: http://webreference.com/programming/java_core/1