parseInt
The parseInt() function gives the integer equivalent of a number and is often used to
make sure that we have a numeric value from the user.
<html>
<!-- Using parseInt -->
<head>
<title> parseInt() </title>
</head>
<body>
<!-- There's no need for a body at all -->
<script>
// Ask for a string and convert it to
// an integer.
first = prompt("Enter a number:", "")
result = parseInt(first)
document.write(result)
</script>
</body>
</html>
Notice that the function is called parseInt - not parseint or ParseInt. JavaScript
is case-sensitive.
Try the program with these values:
The first answer should be 1. Obviously because that's the value we
typed into the prompt.
The second answer should also be 1. As its name suggests, parseInt()
converts the string into an integer and discards the decimal part of
the number. There is a parseFloat() which will give you a floating
point number if that's what you need.
The third answer should be 7. The logic behind parseInt is that it will
do its best. If it sees that the text starts with a number then it will
read in the numeric characters until it reaches something that isn't a
number. In this case it will accept the "7" but stop when it sees the
"U".
The final answer should be NaN. This is a special value that JavaScript
returns when the answer is
not a number.
Using parseInt()
Modify this
example
where the addition sum was failing so that we use parseInt() before adding
the numbers:
<html>
<!-- Calculations -->
<head>
<title> Calculations </title>
</head>
<body>
<!-- There's no need for a body at all -->
<script>
// Ask for two numbers and add them together.
first = prompt("Enter a number:", "")
second = prompt("Enter another number:", "")
// The prompt has give us strings but we need
// numeric values for the addition
firstNumber = parseInt(first)
secondNumber = parseInt(second)
result = firstNumber + secondNumber
document.write (first + " + " + second + " = " + result)
</script>
</body>
</html>
Try entering "1" and "2" again to check that you get the right answer this time.
Try again with some other values.
|