Java Reference
In-Depth Information
type of a piece of data yourself. For example, you may be given a piece of string data that you want
to think of as a number. This is especially likely if you are 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 a situation in which you collect
two numbers from the user using a form and want to calculate their sum. The two numbers are
available to you as strings, for example "22" and "15" . When you try to calculate the sum of these
values using "22" + "15" you get the result "2215" , because JavaScript thinks you are trying to
concatenate two strings rather than trying to find the sum of two numbers. To add to the possible
confusion, the order also makes a difference. So:
1 + 2 + "abc"
results in a string containing "3abc" , whereas:
"abc" + 1 + 2
would result in the string containing "abc12" .
In this section you 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 engine 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.
Converting Strings to Numbers
trY it out
Let's look at an example using parseInt() and parseFloat() . Enter the following code and save it as
ch2 _ example7.html :
<!DOCTYPE html>
<html lang = "en">
<head>
<title>Chapter 2, Example 7</title>
</head>
Search WWH ::




Custom Search