Java Reference
In-Depth Information
The Math object is a little unusual in that JavaScript creates it for you automatically. There's no need
to declare a variable as a Math object or define a new Math object before being able to use it, making
it a little bit easier to use.
The properties of the Math object include some useful math constants, such as the PI property
(giving the value 3.14159 and so on). You access these properties, as usual, by placing a dot after
the object name ( Math ) and then writing the property name. For example, to calculate the area of a
circle, you can use the following code:
var radius = prompt("Give the radius of the circle", "");
var area = Math.PI * radius * radius;
document.write("The area is " + area);
The methods of the Math object include some operations that are impossible, or complex, to perform
using the standard mathematical operators (+, -, *, and /). For example, the cos() method returns
the cosine of the value passed as a parameter. You look at a few of these methods now.
the abs() Method
The abs() method returns the absolute value of the number passed as its parameter. Essentially, this
means that it returns the positive value of the number. So ‐1 is returned as 1 , ‐4 as 4 , and so on.
However, 1 would be returned as 1 because it's already positive.
For example, the following code writes the number 101 to the page:
var myNumber = -101;
document.write(Math.abs(myNumber));
Finding the Largest and Smallest Numbers—the min() and max() Methods
Let's say you have two numbers, and you want to find either the largest or smallest of the two.
To aid you in this task, the Math object provides the min() and max() methods. These methods
both accept at least two arguments, all of which must obviously be numbers. Look at this
example code:
var max = Math.max(21,22); // result is 22
var min = Math.min(30.1, 30.2); // result is 30.1
The min() method returns the number with the lowest value, and max() returns the number with
the highest value. The numbers you pass to these two methods can be whole or floating‐point
numbers.
Note The max() and min() methods can accept many numbers; you're not
limited to two.
rounding Numbers
The Math object provides a few methods to round numbers, each with its own specific purpose.
 
Search WWH ::




Custom Search