Numeric Literals

We learned earlier that a literal is a direct representation of a single, fixed data value. The number type supports three kinds of literals: integer literals, floating-point literals, and special numeric values. The first two literal categories represent real numbers (numbers that have a fixed mathematical value); the third category comprises values that represent numeric concepts such as infinity.

Integer Literals

Integer literals such as 1, 2, 3, 99, and -200, must follow these rules:

  • Integers may not contain a decimal point or fractional value.

  • Integers must not exceed the minimum or maximum legal numeric values of ActionScript. See also the MIN_VALUE and MAX_VALUE properties of the Number object in Part III, for a discussion of legal values.

  • Base-10 integer numbers must not start with a leading zero (e.g., 002, 000023, and 05).

Not all integer values are base-10 (i.e., decimal) integers. ActionScript also supports base-8 (octal) and base-16 (hexadecimal) numeric literals. For a primer on decimal, octal, and hexadecimal numbers, see:

http://www.moock.org/asdg/technotes

We use a leading zero to indicate an octal number. For example, to represent the octal number 723 in ActionScript, we use:

0723  // 467 in decimal (7*64 + 2*8 + 3*1)

To indicate a hexadecimal (hex for short) literal integer, we put 0x (or 0X) in front of the number, such as:

0x723  // 1827 in decimal (7*256 + 2*16 + 3*1)
0xFF   //  255 in decimal (15*16 + 15*1)

Hexadecimal numbers are often used to indicate color values, but most simple programs require only base-10 numbers. Be careful to remove unwanted leading zeros when converting strings to numbers, as shown in Example 4.1.

Example 4-1.  Trim Leading Zeros

function trimZeros(theString) {
  while (theString.charAt(0) == "0" || theString.charAt(0) == " ") {
    theString = theString.substring(1, theString.length);
  }
  return theString;
}

testString = "00377";
trace(trimZeros(testString));  // Displays: 377

Floating-Point Literals

Floating-point literals represent numbers containing fractional parts. A floating-point literal may contain some or all of these four components:

a base-10 integer
a decimal point (.)
a fraction (represented as a base-10 number)
an exponent

The first three components are pretty straightforward: in the number 3.14, “3” is the base-10 integer, “.” is the decimal point, and “14” is the fraction. But the fourth component (the exponent) requires a closer look.

To represent a very large positive or negative number as a float, we can attach an exponent to a number using the letter E (or e). To determine the value of a number with an exponent, multiply the number by 10 to the power specified by the exponent. For example:

12e2    // 1200 (10 squared is 100, times 12 yields 1200)
143E-3  // 0.143 (10 to the power -3 is .001, times 143 yields 0.143)

You may recognize the format as standard scientific notation. If math isn’t your strong point, here’s an easy conversion tip: if the exponent is positive, move the decimal point that many places to the right; if the exponent is negative, move the decimal point that many places to the left.

Sometimes ActionScript will return a number with an exponent as the result of a calculation if the result is a very large or very small value. Note, however, that the exponent E (or e) is merely a notational convenience. If we want to raise a number to an arbitrary power, we use the built-in Math.pow( ) function, which is documented in Part III.

Floating-point precision

Flash uses double-precision floating-point numbers, which offer precision to about 15 significant digits. (Any leading zeros, trailing zeros, and/or exponents are not counted as part of the 15 digits.) This means that Flash can represent the number 123456789012345, but not 1234567890123456. The precision doesn’t limit how big a number can get, only how precise a number can be represented; 2e16 is a bigger number than 123456789012345 but employs only one significant digit.

ActionScript calculations are occasionally rounded in undesirable ways, producing numbers such as 0.14300000000000001 instead of 0.143. This happens because computers convert numbers of any base to an internal binary representation, which can lead to nonterminating fractions in binary (much like 0.3333333 in decimal). Computers have only finite precision, so they cannot perfectly represent nonterminating fractions. In order to accommodate for the minute discrepancy, you should round your numbers manually if the difference will adversely affect the behavior of your code. For example, here we round myNumber to three decimal places:

myNumber = Math.round(myNumber * 1000) / 1000;

And here’s a reusable function to round any number to an arbitrary number of decimal places:

function trim(theNumber, decPlaces) {
  if (decPlaces >= 0) {
    var temp = Math.pow(10, decPlaces);
    return Math.round(theNumber * temp) / temp;
  }
}

// Round a number to two decimal places
trace(trim(1.12645, 2));  // Displays: 1.13

Special Values of the Number Datatype

Integer and floating-point literals account for nearly all the legal values of the number datatype, but there are special keyword values that represent these numeric concepts: Not-a-Number, Minimum Allowed Value, Maximum Allowed Value, Infinity, and Negative Infinity.

Each of the special values may be assigned to variables and properties or used in literal expressions just like any other numeric literal. More often than not, though, the special numeric values are returned by the interpreter as the result of some expression evaluation.

Not-a-Number: NaN

Occasionally, a mathematical computation or an attempted datatype conversion results in a value that is simply not a number. For example, 0/0 is an impossible calculation, and the following expression can’t be converted to a finite number:

23 - "go ahead and try!"

In order to accommodate data that is of the number type but is not a real number, ActionScript provides the NaN keyword value. Though NaN doesn’t represent a number, it is still a legal value of the number type as demonstrated by the following code:

x = 0/0;
trace(x);         // Displays: NaN
trace(typeof x);  // Displays: "number"

Since NaN is not a finite numeric value, it never compares as equal to itself. If two variables hold the value NaN, they are considered not equal (though they may seem equal to us). As a workaround to this problem, we use the built-in function isNaN( ) to check whether a variable contains the NaN value:

x = 12 - "this doesn't make much sense";  // x is now NaN
trace(isNaN(x));                          // Displays: true

Minimum and maximum allowed values: MIN_VALUE and MAX_VALUE

ActionScript represents a broad but not unlimited range of numbers. The maximum allowable value is 1.7976931348623157e+308, and the minimum allowed value is 5e-324. Obviously, those numbers are a bit inconvenient, so we use the special values Number.MAX_VALUE and Number.MIN_VALUE instead.

Number.MAX_VALUE comes in handy when we are checking to see if a calculation results in a representable positive number:

z = x*y;
if (z <= Number.MAX_VALUE && z >= -Number.MAX_VALUE) {
  // Number is legal
}

Note that Number.MIN_VALUE is the smallest positive value allowed, not the largest negative value. The largest negative legal value is -Number.MAX_VALUE.

Infinity and negative infinity: Infinity and -Infinity

If a calculation results in a value larger than Number.MAX_VALUE, ActionScript will use the keyword Infinity to represent the result of the calculation. Similarly, if a calculation results in a value more negative than the largest allowable negative value, ActionScript uses -Infinity to represent the result. Infinity and -Infinity may also be used directly as literal numeric expressions.

Irrational numbers

In addition to the special numeric values NaN, Infinity, -Infinity, Number.MAX_VALUE and Number.MIN_VALUE, ActionScript provides convenient access to mathematical constants via the Math object. For example:

Math.E        // The value of E, the base of the natural logarithm
Math.LN10     // Natural logarithm of 10
Math.LN2      // Natural logarithm of 2
Math.LOG10E   // Base-10 logarithm of e
Math.LOG2E    // Base-2 logarithm of e
Math.PI       // Pi (i.e., 3.1415926...) 
Math.SQRT1_2  // Square root of 1/2
Math.SQRT2    // Square root of 2 (i.e., 1.4142135...)

The constants are simply shorthand forms of floating-point values that approximate commonly used irrational numbers. You can use these irrational numbers just as you would any other object property:

area = Math.PI*(radius*radius);

For a complete list of supported constants, see the Math object in Part III.

Get ActionScript: The Definitive Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.