Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Arithmetic Operation On Two Variables

Status
Not open for further replies.

thebull1

Programmer
Oct 24, 2001
68
I'm a novice in Javascript and I have run into a small problem.
How do you for example perform var1 + var2 ?? When I do this I get a concatenation of the two variables...eg if var1=5 and var2=6, var1 + var2 gives me 56 and not 11. How do I go round this??
 
If var1=5 and var2=6, the statement var1+var2 will give 11, unless one of the two is actually a string (var1="5" or var2="6").

Try using parseInt("" + var1) + parseInt("" + var2). The adding of the "" will ensure that both are strings, and therefore you should get no errors on this. Never too old to learn...
Nico
 
Thanks nvb! The parseInt is a perfect solution!
 
If it's any consolation, the fact that JavaScript is not strongly typed proves especially irascible at times. It seems to be some of my most subtle errors, particularly because in the application I'm working on, I use strings of digits to represent numbers and I have to keep them as strings.

Keep parseInt handy!

Cheers,

Edward "Do not read this sentence."
 
yea or if you forget the word parseInt... you can always multiply 'em both by one and add them ... ie:
Code:
var one = 1;
var two = 2;
var three = (one * 1) + (two * 1);

that just verifies they are both integers. Suceess, thats the way you spell success!
Got a question? Ask IMOZRMY!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top