JavaScript Editor JavaScript Validator     JavaScript Editor 



Team LiB
Previous Section Next Section

Data Type Conversion

As we saw, if you add a string and a number together, JavaScript makes the sensible choice and converts the number to a string, then concatenates the two. Usually JavaScript has enough sense to make data type conversions like this whenever it needs to, but there are some situations where we need to convert the type of a piece of data ourselves. For example, we may be given a piece of string data that we want to think of as a number. This is especially true in the case of using forms to collect data from the user. Any values input by the user are treated as strings, even though they may contain numerical data, such as the user's age.

Why is changing the type of the data so important? Consider the following situation where we collect two numbers from the user using a form and want to calculate their sum. The two numbers are available to us as strings, for example "22" and "15". When we try to calculate the sum of these values using "22" + "15" we get the result "2215", because JavaScript thinks we are trying to concatenate two strings rather than trying to find the sum of two numbers.

In this section we'll look at two conversion functions that convert strings to numbers: parseInt() and parseFloat().

Let's take parseInt() first. This function takes a string and converts it to an integer. The name is a little confusing at first—why parseInt() rather than convertToInt()? The main reason for the name comes from the way that the function works. It actually goes through (that is, parses) each character of the string you ask it to convert and sees if it's a valid number. If it is valid, parseInt() uses it to build up the number; if it is not valid, the command simply stops converting and returns the number it has converted so far.

For example, if your code is parseInt("123"), JavaScript will convert the string "123" to the number 123. For the code parseInt("123abc"), JavaScript will also return the number 123. When the JavaScript interpreter gets to the letter a, it assumes the number has ended and gives 123 as the integer version of the string "123abc".

The parseFloat() function works in the same way as parseInt(), except that it returns floating-point numbers—fractional numbers—and that a decimal point in the string, which it is converting, is considered to be part of the allowable number.

Try It Out – Converting Strings to Numbers

Let's look at an example using parseInt() and parseFloat(). Type in the following code and save it as ch2_examp7.htm.

<html>
<body>
    
<script language="JavaScript" type="text/javascript">
    
var myString = "56.02 degrees centigrade";
var myInt;
var myFloat;
    
document.write("\"" + myString + "\" is " + parseInt(myString) +
   " as an integer" + "<br>");
    
myInt = parseInt(myString);
document.write("\"" + myString + "\" when converted to an integer equals " +
   myInt + "<br>");
    
myFloat = parseFloat(myString);
document.write("\"" + myString +
   "\" when converted to a floating point number equals " + myFloat);
    
</script>
    
</body>
</html>

Load it into your browser, and you'll see three lines written in the web page as shown in Figure 2-13.

Click To expand
Figure 2-13

How It Works

Our first task in the script block is to declare some variables. The variable myString is declared and initialized to the string we want to convert. We could just as easily have used the string directly in this example rather than storing it in a variable, but in practice you'll find that you use variables more often than literal values. We also declare the variables myInt and myFloat, which will hold the converted numbers.

var myString = "56.02 degrees centigrade";
var myInt;
var myFloat;

Next, we write to the page the converted integer value of myString displayed inside a user-friendly sentence we build up using string concatenation. Notice that we use the escape sequence \" to display quotes (") around the string that we are converting.

document.write("\"" + myString + "\" is " + parseInt(myString) +
   " as an integer" + "<br>");

As you can see, you can use parseInt() and parseFloat() in the same places you would use a number itself or a variable containing a number. In fact, in this line the JavaScript interpreter is doing two conversions. First it converts myString to an integer, because that's what we asked for by using parseInt(). Then it automatically converts that integer number back to a string, so it can be concatenated with the other strings to make up our sentence. Also note that only the 56 part of the myString variable's value is considered a valid number when dealing with integers. Anything after the 6 is considered invalid and is ignored.

Next we do the same conversion of myString using parseInt(), but this time we store the result in the myInt variable. On the following line we use the result in some text we display to the user.

myInt = parseInt(myString);
document.write("\"" + myString + "\" when converted to an integer equals " +
   myInt + "<br>");

Again, though myInt holds a number, the JavaScript interpreter knows that +, when a string and a number are involved, means we want the myInt value converted to a string and concatenated to the rest of the string so it can be displayed.

Finally, we use parseFloat() to convert the string in myString to a floating-point number, which we store in the variable myFloat. This time the decimal point is considered to be a valid part of the number, so it's anything after the 2, which is ignored. Again we use document.write() to write the result to the web page inside a user-friendly string.

myFloat = parseFloat(myString);
document.write("\"" + myString +
   "\" when converted to a floating point number equals " + myFloat);

Dealing with Strings That Won't Convert

Some strings simply are not convertible to numbers, such as strings that don't contain any numerical data. What happens if we try to convert these strings? As a little experiment, try changing the preceding example so that myString holds something that is not convertible. For example, change the line

var myString = "56.02 degrees centigrade";

to

var myString = "I'm a name not a number";

Now reload the page in your browser and you should see what's shown in Figure 2-14.

Click To expand
Figure 2-14

You can see that in the place of the numbers we got before, we get NaN. What sort of number is that? Well, it's Not a Number at all!

If you use parseInt() or parseFloat() with any string that is empty or does not start with at least one valid digit, you get NaN, meaning Not a Number.

NaN is actually a special value in JavaScript. It has its own function, isNaN(), which checks whether something is NaN or not. For example

myVar1 = isNaN("Hello");

will store the value true in the variable myVar1, since "Hello" is not a number, whereas

myVar2 = isNaN(34);

will store the value false in the variable myVar2, since 34 can be converted successfully from a string to a number by the isNaN() function.

In the next chapter we'll see how you can use the isNaN() function to check the validity of strings as numbers, something that proves invaluable when dealing with user input, as we'll see in Chapter 6.


Team LiB
Previous Section Next Section


JavaScript Editor JavaScript Validator     JavaScript Editor


©