Java Reference
In-Depth Information
In this section you'll look at two conversion functions that convert strings to numbers: parseInt() and
parseFloat().
Let's take parseInt() fi rst. This function takes a string and converts it to an integer. The name is a
little confusing at fi rst — 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 fl oating-point
numbers — fractional numbers — and that a decimal point in the string, which it is converting, is con-
sidered to be part of the allowable number.
Try It Out Converting Strings to Numbers
Let's look at an example using parseInt() and parseFloat(). Enter the following code and save it as
ch2_examp7.htm:
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<body>
<script 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>
Search WWH ::




Custom Search