Java Reference
In-Depth Information
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 fi nd 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 fl oating point numbers.
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 specifi c purpose.
The ceil() Method
The ceil() method always rounds a number up to the next largest whole number or integer. So 10.01
becomes 11, and -9.99 becomes -9 (because -9 is greater than -10). The ceil() method has just one
parameter, namely the number you want rounded up.
Using ceil() is different from using the parseInt() function you saw in Chapter 2, because parseInt()
simply chops off any numbers after the decimal point to leave a whole number, whereas ceil() rounds
the number up.
For example, the following code writes two lines in the page, the fi rst containing the number 102 and
the second containing the number 101:
var myNumber = 101.01;
document.write(Math.ceil(myNumber) + “<br />”);
document.write(parseInt(myNumber));
The f oor() Method
Like the ceil() method, the floor() method removes any numbers after the decimal point, and
returns a whole number or integer. The difference is that floor() always rounds the number down. So
if you pass 10.01 you will be returned 10, and if you pass -9.99 you will see -10 returned.
Search WWH ::




Custom Search