Converting Between Data Types
JavaScript handles conversions between data types for you whenever it can. For example, you've already used statements like this:
document.write("The total is " + total);
This statement prints out a message such as "The total is 40". Because the document.write function works with strings, the JavaScript interpreter automatically converts any nonstrings in the expression (in this case, the value of total) to strings before performing the function.
This works equally well with floating-point and Boolean values. However, there are some situations where it won't work. For example, the following statement will work fine if the value of total is 40:
However, the total variable could also contain a string; in this case, the preceding statement would result in an error.
In some situations, you might end up with a string containing a number, and need to convert it to a regular numeric variable. JavaScript includes two functions for this purpose:
Both of these functions will read a number from the beginning of the string and return a numeric version. For example, these statements convert the string "30 angry polar bears" to a number:
stringvar = "30 angry polar bears";
numvar = parseInt(stringvar);
After these statements execute, the numvar variable contains the number 30. The nonnumeric portion of the string is ignored.
By the Way
These functions look for a number of the appropriate type at the beginning of the string. If a valid number is not found, the function will return the special value NaN, meaning not a number.
|