2.1 Converting Between Numbers and Strings
NN 4, IE 4
2.1.1 Problem
You want to change a number data
type to a string data type, or vice versa.
2.1.2 Solution
To convert a number value to a string value in Version 4 or later
browsers, use the toString(
) method of a number value:
var numAsStringValue = numValue.toString( );
You can also create an instance of a String object
by passing the number as an argument to the String
object constructor:
var numAsStringObject = new String(numValue);
To convert a string to a number, use the parseInt(
) method if the desired result is an
integer only, or the parseFloat(
) method if the number could be or is
definitely a floating-point number:
var intValue = parseInt(numAsString, 10);
var floatValue = parseFloat(numAsString);
If you use parseFloat( ) and the number passed as
an argument is an integer, the result will also be formatted as an
integer, without a decimal and trailing zero. Both the
parseInt( ) and parseFloat( )
functions work with all scriptable browser versions.
2.1.3 Discussion
In many cases, the JavaScript interpreter tries to cast values
between number and string data types automatically. For example, if
you multiply a number times a string version of the number, the
string is automatically converted to a number value, and the
operation succeeds. This kind of casting doesn't
always work, however. For instance, the addition (+)
operator plays two roles in JavaScript: adding numbers and
concatenating strings. When you place this operator between a number
and a number that is actually a string value, the string wins the
battle, and the two numbers get concatenated together as a string.
Thus, the expression 2 +
"2" equals "22" in JavaScript.
Most commonly, you need to convert a string to a numeric value when
you perform math operations on values entered by the user in form
text boxes. The value
property of any text field supplies the data as a string value. To
add values from two text boxes to fill a third requires converting
each operand to a number before doing the math. Then you can assign
the resulting number value to the value property
of the third text box, where the number automatically converts to a
string value because that's the only data type
acceptable in a text box. For example:
var val1 = parseFloat(document.myForm.firstNum.value);
var val2 = parseFloat(document.myForm.secondNum.value);
var result = val1 + val2;
document.myForm.sum.value = result;
Unlike most other programming languages, JavaScript does not
differentiate numeric data types by the kind of
number. A number is a number, whether it happens to be an integer or
a floating-point number. The distinction made by the two number
parsing methods is that even if the source string contains a number
with a decimal point and digits to the right of the decimal, only the
integer portion is returned from parseInt( ). This
behavior comes in handy when the source string starts with a number
but has additional string characters following it. For example, the
navigator.appVersion property returns a string
similar to the following:
4.0 (compatible; MSIE 6.0; Windows 98; Q312461)
If you want to get the integer that starts this string, you can apply
the parseInt( ) method:
var mainVer = parseInt(navigator.appVersion, 10);
Similarly, if the string starts with a floating-point number (say,
4.2), you could use parseFloat(
) to get a numeric copy of just the
leading number. In other words, both methods try to grab as much of
their kinds of numbers as they can from the front of the string. When
they encounter a nonnumeric value, the copying stops, and they return
whatever number has been collected up to that point.
It's a good idea to specify the optional second
parameter to parseInt( ) as a
10, signifying that you want the value treated as
a base-10 value. If you don't, and the string begins
with a zero and either an 8 or 9, the string number is treated as an
octal value (whose allowable digits are 0 through 7), and the 8 and 9
digits are treated as nonnumeric. The parseFloat(
) method always returns a base-10 value (see Recipe 2.6).
As for converting a number to a string, an old trick from the
earliest days of JavaScript still works. It's simply
an extrapolation of the behavior just explained that forces the
addition operator to give priority to string concatenation over
numeric addition. If you "add" an
empty string to a number value, the result of the operation is a
string version of that number:
var numAsString = numVal + "";
The syntax isn't particularly elegant, but it is
compact and fully backward-compatible. If you see this construction
in some old code, now you know where it comes from.
2.1.4 See Also
Recipe 2.6 for converting between different number bases.
|