Java Reference
In-Depth Information
Load it into your browser, and you'll see three lines written in the web page, as shown in Figure 2-9.
“56.02 degrees centigrade” is 56 as an integer
“56.02 degrees centigrade” when converted to an integer equals 56
“56.02 degrees centigrade” when converted to a floating point number equals 56.02
Figure 2-9
You r fi rst task in the script block is to declare some variables. The variable myString is declared and
initialized to the string you want to convert. You could just as easily have used the string directly in
this example rather than storing it in a variable, but in practice you'll fi nd that you use variables more
often than literal values. You also declare the variables myInt and myFloat , which will hold the con-
verted numbers.
var myString = “56.02 degrees centigrade”;
var myInt;
var myFloat;
Next, you write to the page the converted integer value of myString displayed inside a user-friendly
sentence you build up using string concatenation. Notice that you use the escape sequence \” to display
quotes (“) around the string you 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 you 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 your sentence. Also note that only the 56 part of the myString variable's
value is considered a valid number when you're dealing with integers. Anything after the 6 is consid-
ered invalid and is ignored.
Next, you do the same conversion of myString using parseInt(), but this time you store the result in
the myInt variable. On the following line you use the result in some text you 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 you want the myInt value converted to a string and concatenated to the
rest of the string so it can be displayed.
Finally, you use parseFloat() to convert the string in myString to a fl oating-point number, which
you 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 that is ignored. Again you 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);
Search WWH ::




Custom Search