﻿ Converting to a number ﻿

Main Page

# Converting to a number

Calling
toString(10)
on a number is the same as calling
toString()
; they both return the deci-
mal equivalent of the number.
Converting to a number
ECMAScript provides two methods for converting non-number primitives into numbers:
parseInt()
and
parseFloat()
. As you may have guessed, the former converts a value into an integer whereas the
latter converts a value into a floating-point number. These methods only work properly when called on
strings; all other types return
NaN
.
Both
parseInt()
and
parseFloat()
look at a string carefully before deciding what its numeric value
should be. The
parseInt()
method starts with the character in position 0 and determines if this is a
valid number; if it isn’t, the method returns
NaN
and doesn’t continue. If, however, the number is valid,
the method goes on to the character in position 1 and does the same test. This process continues until
a character isn’t a valid number, at which point
parseInt()
takes the string (up to that point) and
converts it into a number. For example, if you want to convert the string
“1234blue”
to an integer,
parseInt()
would return a value of
1234
because it stops processing one it reaches the character
b
.
Any number literal contained in a string is also converted correctly, so the string
“0xA”
is properly con-
verted into the number 10. However, the string
“22.5”
will be converted to
22
, because the decimal
point is an invalid character for an integer. Some examples:
var iNum1 = parseInt(“1234blue”); //returns 1234
var iNum2 = parseInt(“0xA”); //returns 10
var iNum3 = parseInt(“22.5”); //returns 22
var iNum4 = parseInt(“blue”); //returns NaN
The
parseInt()
method also has a radix mode, allowing you to convert strings in binary, octal, hexa-
decimal, or any other base into an integer. The radix is specified as a second argument to
parseInt()
,
so a call to parse a hexadecimal value looks like this:
var iNum1 = parseInt(“AF”, 16); //returns 175
Of course, this can also be done for binary, octal, and even decimal (which is the default mode):
var iNum1 = parseInt(“10”, 2); //returns 2
var iNum2 = parseInt(“10”, 8); //returns 8
var iNum2 = parseInt(“10”, 10); //returns 10
If decimal numbers contain a leading zero, it’s always best to specify the radix as 10 so that you won’t
accidentally end up with an octal value. For example:
var iNum1 = parseInt(“010”); //returns 8
var iNum2 = parseInt(“010”, 8); //returns 8
var iNum3 = parseInt(“010”, 10); //returns 10
In this code, both lines are parsing the string
“010”
into a number. The first line thinks that the string is
an octal value and parses it the same way as the second line (which specifies the radix as 8). The last line
specifies a radix of 10, so
iNum3
ends up equal to 10.
23
ECMAScript Basics
05_579088 ch02.qxd 3/28/05 11:35 AM Page 23

Free JavaScript Editor     Ajax Editor