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

Computer Problems? Computing.Net has over 1,000,000 posts about all things technology related! Over 90% answered within 24 hours! Click here to start participating now! Also, be sure to check out the New User Guide.

Javascript addition problem.

Reply to Message Icon

Name: Prongs73180
Date: June 4, 2006 at 16:04:55 Pacific
OS: Windows XP SP2
CPU/Ram: 256 MB
Product: 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/



Sponsored Link
Ads by Google

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

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


0

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

That worked perfect :D Thanks for your help.


0

Sponsored Link
Ads by Google
Reply to Message Icon

Related Posts

See More







Post Locked

This post is quite old and has been locked from receiving new replies. Please create a new posting instead.


Go to Programming Forum Home


Sponsored links

Ads by Google


Results for: Javascript addition problem.

Javascript syntax problem? www.computing.net/answers/programming/javascript-syntax-problem/11162.html

Why maximize is problem for C++ 3.0 www.computing.net/answers/programming/why-maximize-is-problem-for-c-30/13323.html

Programming in C www.computing.net/answers/programming/programming-in-c/9073.html