|[ Team LiB ]|
2.1 Converting Between Numbers and Strings
NN 4, IE 4
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);
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.
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;
4.0 (compatible; MSIE 6.0; Windows 98; Q312461)
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).
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.
|[ Team LiB ]|