Print this Section


The Math Object

The Document Object Model includes built-in objects besides those associated with specific elements of a Web page. One of these built-in objects is the Math object, which includes methods to perform mathematical calculations. These methods can be used in combination with the arithmetic operators covered previously.

The following table shows some useful mathematical methods. For each of the methods, an arithmetic expression is supplied to which the method is applied. An expression can be a number, a variable containing a numeric value, or a combination of arithmetic operations that produces a numeric result. In this table, literal numeric values are supplied to the methods as examples.

Method Description Returns
Math.abs(expression) Returns the absolute (non-negative) value of a number:

Math.max(expr1,expr2) Returns the greater of two numbers:
Math.min(expr1,expr2) Returns the lesser of two numbers:

Math.round(expression) Returns a number rounded to nearest integer (.5 rounds up):

Math.ceil(expression) Returns the next highest integer value above a number:

Math.floor(expression) Returns the next lowest integer value below a number:

Math.pow(x,y) Returns the y power of x:

Math.sqrt(expression) Returns the square root of a number:

Math.random() Returns a random number between zero and one:

Figure 2-23. Methods of the Math object.

It is not necessary at this point to go into detail about all of these Math methods. There will be occasion throughout the tutorials to review their uses as needed. You can refer back to this page for reminders of their syntax. That said, there are a few of these methods that you might find generally useful and deserving of introductory comments.

Rounding Numbers

Previously, you were introduced to the toFixed() method that can be applied to numeric values to round them to the nearest decimal digit. In a similar vein, the Math object's round(), ceil(), and floor() methods perform rounding, but to integer values rather than to decimal precisions.

Math.round() rounds up to the next highest integer when the first decimal position in a floating-point number is .5 or greater; otherwise it rounds down. In contrast, Math.ceil() always rounds up to the next highest integer and Math.floor() always rounds down to the next lower integer. Use of these latter two rounding methods comes into play when generating random numbers, described below.

The need to round to integer numbers occurs frequently when calculating screen positions or maintaining size proportionality of objects. Positions and sizes must be in whole pixel measurements. For instance, the following picture has an original size of 225 x 150 pixels, making the ratio of the height to the width 2/3. When resizing the image, proportionality is maintained by setting the height to .667 times its width. If the width is changed to 125 pixels, then the height is calculated as 83.375 pixels, which needs to be rounded to 83 pixels since there are no partial pixels on the screen.

Figure 2-24. Resizing an image proportionately.

The following script shows the calculations and settings for resizing the previous picture.

function Resize() {
  var NewWidth = parseInt(prompt("Enter new width:", ""));
  var NewHeight = Math.round(NewWidth * .667);
  document.getElementById("Pic").style.width = NewWidth + "px";
  document.getElementById("Pic").style.height = NewHeight + "px";

Listing 2-16. Code to resize an image proportionately.

The user enters a new width setting through a prompt box. The parseInt() method is applied to the entered value to ensure it is an integer number. The width is multiplied by .667 to calculate the proportionate height, and the Math.round() method is applied to the calculated height to convert it to an integer value. These new width and height values are assigned to the width and height style properties of the image.

Random Numbers

A useful method is Math.random(), which returns a random number between 0 and 1. The need for random numbers comes up in various types of computer games, in experimental research to assign subjects to groups, in drawing a sample of individuals from a population, in generating numbers to test software, and in other scenarious with a need for unbiased numbers. A common use, for example, is to select numbers from a telephone book for conducting surveys.

Often, you are looking for a random number between 1 and some upper limit, say, between 1 and 10 or between 1 and 100. You can produce this number with the following formula:

Math.ceil(Math.random() * upper limit)

Multiply the random number generated by JavaScript by the highest number in the desired range, and round the value up to the nearest integer using the Math.ceil() function. For example, the following button generates a random number between 1 and 10.

More generally, to generate a random number between a low and high value inclusively, use the formula:

Math.floor((upper limit - lower limit + 1) * Math.random() + lower limit)

The lower limit is the smallest number in the desired range, and upper limit is the largest number in the range. Math.floor() is applied to the generated number to round down to the nearest integer to offset the lower limit + 1 calculation. The following button, for example, generates a random number between 100 and 999.

It is difficult to summarize or generalized the varied uses of the Math object's methods; they have applicability in about every field of endeavour. Later, a few of the ways to apply selected methods as they relate narrowly to techniques that are introduced.

TOP | NEXT: String Objects