4.3 Numeric Literals

ActionScript for Flash MX: The Definitive Guide, 2nd Edition
By Colin Moock
Chapter 4.  Primitive Datatypes

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.

4.3.1 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 the MIN_VALUE and MAX_VALUE properties of the Number object in the Language Reference for a discussion of legal values.

  • Base-10 integer numbers must not start with a leading zero (e.g., these are not valid base-10 integers: 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/basePrimer/

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"

4.3.2 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 fractional portion (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" (i.e., 14 one-hundredths) is the fractional portion. But the fourth component (the exponent) requires a closer look.

To represent a very large positive or negative number as a float, we can append 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 (a.k.a. exponential 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.

ActionScript may 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 the ActionScript Language Reference.

4.3.2.1 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 precisely a number can be represented; 2e16 is a bigger number than 123456789012345, but it employs only one significant digit.

Occasionally, ActionScript calculations are 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 compensate 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 roundNum (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(roundNum(1.12645, 2));  // Displays: 1.13

4.3.3 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 the following numeric concepts: Not-a-Number, Minimum Allowed Value, Maximum Allowed Value, Infinity, and Negative Infinity.

Each of the special values can 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.

4.3.3.1 Not-a-Number: NaN

Occasionally, a mathematical computation or an attempted datatype conversion results in a value that simply is 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 calculable number, ActionScript provides the NaN keyword value. Though NaN doesn't represent a calculable 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). To work around 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
4.3.3.2 Minimum and maximum allowed values: MIN_VALUE and MAX_VALUE

ActionScript can represent a broad, but not unlimited, range of numbers. The maximum allowable value is 1.79769313486231e+308, and the minimum allowed value is 4.94065645841247e-324. Obviously, these numbers are cumbersome, so ActionScript offers the special values Number.MAX_VALUE and Number.MIN_VALUE for convenience.

Number.MAX_VALUE comes in handy when we are checking to see if a calculation results in a representable 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 most negative value. The "largest" negative legal value is -Number.MAX_VALUE.

4.3.3.3 Infinity and negative infinity: Infinity and -Infinity

If a calculation results in a value larger than Number.MAX_VALUE, ActionScript uses the keyword Infinity to represent the result of the calculation (this is known as an overflow condition). Similarly, if a calculation results in a value more negative than the "largest" allowable negative value, ActionScript uses -Infinity to represent the result (this is known as an underflow condition). Infinity and -Infinity can also be used directly as literal numeric expressions.

4.3.3.4 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...)

These constants are simply shorthand forms of floating-point values that approximate commonly used irrational numbers. (Irrational numbers, by definition, are numbers that cannot be represented by a simple fraction, such as 1/3. They should not be confused with NaN, Infinity, etc.) 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 the Language Reference.

     



    ActionScript for Flash MX. The Definitive Guide
    ActionScript for Flash MX: The Definitive Guide, Second Edition
    ISBN: 059600396X
    EAN: 2147483647
    Year: 2002
    Pages: 780
    Authors: Colin Moock

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net