Javascript addition problem.

June 4, 2006 at 16:04:55
Specs: Windows XP SP2, 256 MB

I just started learning Javascript (I mean just, as in yesterday, the 3rd), and tried to make a simple addition program. First, it'll prompt you asking how many numbers you'd like to add. That part works fine, as long as a number is entered. Then, it'll ask you for how many ever numbers you selected. Then comes the problem. It adds them as strings, like 3 + 2 + 1 would equal 321. What am I doing wrong? A page with the program in question listed below.

See More: Javascript addition problem.

Report •

June 4, 2006 at 19:09:37

Javascript is very relaxed on how it handles strings and numbers. For instance you can add strings and numbers. In this instance javascript is handling the input as strings. So, you could do one of two things. 1) ensure that the input values are handles as numbers or 2)ensure the adition is handled as numbers. The solutin is basically the same either way.

I'd go with the first option as that would corerct the issue at the earliest point. Do it by adding the line in blue:

var num1 = prompt("Which number would you like to add? ","");
num1 = num1 * 1;
sum += num1;

By putting the multiplication in, you force JavaScript to treat it as a number.

Michael J

Report •

June 4, 2006 at 19:34:11

That worked perfect :D Thanks for your help.

Report •

Related Solutions

Ask Question