Computing.Net > Forums > Programming > Javascript addition problem.

Javascript addition problem.

Reply to Message Icon

Original Message
Name: Prongs73180
Date: June 4, 2006 at 16:04:55 Pacific
Subject: Javascript addition problem.
OS: Windows XP SP2
CPU/Ram: 256 MB
Model/Manufacturer: Dell
Comment:

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.

http://www.freewebs.com/myhtmltestpage/


Report Offensive Message For Removal


Response Number 1
Name: Michael J (by mjdamato)
Date: June 4, 2006 at 19:09:37 Pacific
Reply: (edit)

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 Offensive Follow Up For Removal

Response Number 2
Name: Prongs73180
Date: June 4, 2006 at 19:34:11 Pacific
Reply: (edit)

That worked perfect :D Thanks for your help.


Report Offensive Follow Up For Removal







Use following form to reply to current message:

   Name: From My Computing.Net Settings
 E-Mail: From My Computing.Net Settings

Subject: Javascript addition problem.  

Comments:

 


  Homepage URL (*): 
Homepage Title (*): 
         Image URL: 
 
Data Recovery Software




Have you ever used OpenOffice?

Yes, as my main suite.
Yes, occationally.
Yes, but only once.
No, never.


View Results

Poll Finishes Today.
Discuss in The Lounge