Main Page

directly (not accessed from another variable). For example, the following line of code declares a variable
to hold an integer value, which is defined by the literal
55
:
var iNum = 55;
Integers can also be represented as either octal (base 8) or hexadecimal (base 16) literals. For an octal lit-
eral, the first digit must be a zero (0), and the following digits can be any octal digit (0 through 7), as in
this line of code:
var iNum = 070; //070 is equal to 56 in decimal
To create a hexadecimal literal, the first digit must be a zero (0) followed by the letter x, followed by any
number of hexadecimal digits (0-9 and A-F). The digits may be in uppercase or lowercase. For example:
var iNum = 0x1f; //0x1f is equal to 31 in decimal
var iNum2 = 0xAB; //0xAB is equal to 171 in decimal
To define a floating-point value, you must include a decimal point and one digit after the decimal point
(for instance, use 1.0 not 1.). This is considered a floating-point number literal. Example:
var fNum = 5.0;
The interesting thing about this form of floating-point literal is that it is actually stored as a string until
it’s needed for calculation.
For very large or very small numbers, floating-point values can be represented using
e-notation
. In
e-notation, a number is represented by digits (including decimal digits), followed by an
e
(or an
E
),
followed by the number of times to multiply it by 10. Confused? Here’s an example:
var fNum = 3.125e7;
This notation represents the number 31250000. You can get this value by converting the e-notation to a
calculation: 3.125
?
10
7
, which is exactly equal to 3.125
?
10
?
10
?
10
?
10
?
10
?
10
?
10.
E-notation can also be used to represent very small numbers, such as 0.00000000000000003, which can be
written as 3e-17 (here, 10 is raised to the –17 power, meaning that you will actually be dividing by 10 17
times). ECMAScript, by default, converts any floating-point number with six or more leading zeros into
e-notation.
Floating-point values are stored in a 64-bit IEEE 754 format, meaning that decimal
values can have up to 17 decimal places. After that, the values are truncated, result-
ing in small mathematical errors.
Even though integers can be represented as octal and hexadecimal literals, all mathe-
matical operations return decimal results.
19
ECMAScript Basics
05_579088 ch02.qxd 3/28/05 11:35 AM Page 19

Free JavaScript Editor     Ajax Editor