PDA

View Full Version : data types in javascript


bsoto8168
10-17-2002, 06:31 PM
I have a javascript assignment that needs me to display two prompts. Each prompt asks for a number between 1 to 100. After the 2 numbers from each prompt are inputed they must be totaled and the total must be displayed on the screen.

My problem is having the script read the numbers as integers so the calculation can be done. Whats happening instead is the two numbers that I type into the prompts are being concantenated instead of being added to each other. Here is my code below:

<script>
var firstnum = prompt ("Enter a number beween 1 and 100");

var secondnum = prompt (" Enter a second number between 1 and 100");

var total = 0;

total = firstnum + secondnum;

document.writeln (total);

</script>

It is the 3 rd prompt box (Ex 1.1)

http://matrix.csis.pace.edu/~f02-cs156-s18/

Roelf
10-17-2002, 06:36 PM
try finding your answer in this thread

http://www.codingforums.com/showthread.php?s=&threadid=8129

beetle
10-17-2002, 06:42 PM
There are two ways to extract an integer from a piece of data.

number() and parseInt()

parseInt() is the preferred.

var num = "3";
num = parseInt(num)

or

var num = parseInt("3");

Also, parseInt can take an extra parameter, specifying the base.

var base5 = parseInt("12",5);

although it's rarely used.

Roy Sinclair
10-17-2002, 08:47 PM
Originally posted by beetle

...
Also, parseInt can take an extra parameter, specifying the base.

var base5 = parseInt("12",5);

although it's rarely used.

Whoa there! The base should almost always be specified, otherwise the silly routine will take inputs with leading zeroes as octal which will trip up a lot of people and lead to unexpected results. What you should have said is that a base other than 10 is rarely specified.

beetle
10-17-2002, 09:24 PM
right

adios
10-18-2002, 01:58 AM
Why not just stop at that link (Roelf's, above)? Nice thread. Might encourage people to search occasionally...