• Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

Chapter 4. Primitive Datatypes > Working with Numbers

4.4. Working with Numbers

We can manipulate numbers by combining them with operators to form mathematical expressions and by calling built-in functions to perform complex mathematical operations.

4.4.1. Using Operators

Basic arithmetic—addition, subtraction, multiplication, and division—is accomplished using the +, -, *, and / operators. Operators can be used with any numeric literals or data containers such as variables. Mathematical expressions are evaluated in the order determined by the precedence of the operators, as shown in Table 5-1. For example, multiplication is performed before addition. All of these are legitimate uses of mathematical operators:

x = 3 * 5;            // Assign the value 15 to x
x = 1 + 2 - 3 / 4;    // Assign the value 2.25 to x
x = 56;
y = 4 * 6 + x;        // Assign the value 80 to y
y = x + (x * x) / x;  // Assign the value 112 to y

4.4.2. Built-in Mathematical Functions

To perform advanced math, we use the built-in mathematical functions of the Math object. For example:

Math.abs(x)       // Absolute value of x
Math.min(x, y)    // The smaller of the values x and y
Math.pow(x, y)    // x raised to the power y
Math.round(x)     // x rounded to the nearest integer

These math functions return values that we use in expressions, just as we use literal numbers. For example, suppose we want to simulate a six-sided die. We can use the Math.random( ) function to retrieve a random float between 0 and 0.999 . . . :

dieRoll = Math.random();

Then, we multiply that value by 6, giving us a float between 0 and 5.999, to which we add 1:

dieRoll = dieRoll * 6 + 1;  // Sets dieRoll to a number between 1 and 6.999

Finally, we use the floor( ) function to round our number down to the closest integer:

dieRoll = Math.floor(dieRoll);  // Sets dieRoll to a number between 1 and 6

Condensed into a single expression, our die roll calculation looks like this:

// Sets dieRoll to a number between 1 and 6 inclusive
dieRoll = Math.floor(Math.random() * 6 + 1); 

  • Creative Edge
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint