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 Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

make an input number a number to be added 1

Status
Not open for further replies.

project3

Technical User
Jan 10, 2008
22
US
I have two input values on from a text box and one from select box. I store them as x and y.
x = 7.95
y = 5.95

then when I try to add them z = x + y;
z becomes 7.955.95 how do I decalre them as numbers.
 
I just multiply the string by * 1 to make it a number. I figured that out when the multiplications were working.

so like x = x * 1
 
<input> values are read as strings, so, like you discovered, you have to convert them to numbers first. You can use the method you came up with, or use
Code:
var z = parseFloat(x) + parseFloat(y);

For integers, you'd use parseInt(variable, base).

Lee
 
I'd suggest going with Lee's solution, as it is more intuitive to what you are trying to accomplish. Javascript provides us with these functions specifically for the purpose of converting strings into numbers. You can achieve the same effect by multiplying by 1, dividing by 1, or subtracting 0 (basically any math function besides + because strings see that as concatenation) - however, coding like this can become very ugly and it's not too fun to maintain - unfortunately I know this from experience (yes, I'm talking about you, Uncle Rico). When you look at your code and you see parseInt or parseFloat it is very clear what you are trying to accomplish. If you're in some competition to complete a task in the least amount of bytes possible then the tricks above will work, but from a production standpoint where others may have to help maintain the code, do everybody a favor and do it the "right" way.

Ok, off my [soapbox] now.

-kaht

Lisa, if you don't like your job you don't strike. You just go in every day and do it really half-assed. That's the American way. - Homer Simpson

[small]<P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <.</B>[/small]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top