The sum of two input fields

E

Ebbe

I cant seem to calculate the sum with:
document.forms[0].boxOne.value + 0.5*document.forms[0].boxTwo.value

If boxOne contains "1", and boxTwo "3" then the line above prints 11.5..
And thats not the sum..

Can anyone help?


Ebbe
 
E

Evertjan.

Ebbe wrote on 10 mei 2004 in comp.lang.javascript:
I cant seem to calculate the sum with:
document.forms[0].boxOne.value + 0.5*document.forms[0].boxTwo.value

If boxOne contains "1", and boxTwo "3" then the line above prints 11.5..
And thats not the sum..

x = +document.forms[0].boxOne.value + 0.5*document.forms[0].boxTwo.value
 
F

Fred Basset

What is happening is that the Javascript is treating your plus symbol as
a concatenation operator rather than an addition one, so it believe it
is being told to contatenate "1" and "1.5" (half of 3) ... i.e. "11.5"

What you need to do is to explicitly state that the two things to be
added are numbers, forcing Javascript to add them rather than
concatenating them.


parseFloat( document.forms[0].boxOne.value ) + parseFloat( 0.5 *
document.forms[0].boxTwo.value )


Fred Basset
(e-mail address removed)
 
L

Lee

Fred Basset said:
What is happening is that the Javascript is treating your plus symbol as
a concatenation operator rather than an addition one, so it believe it
is being told to contatenate "1" and "1.5" (half of 3) ... i.e. "11.5"

What you need to do is to explicitly state that the two things to be
added are numbers, forcing Javascript to add them rather than
concatenating them.


parseFloat( document.forms[0].boxOne.value ) + parseFloat( 0.5 *
document.forms[0].boxTwo.value )

That second term is a bit inefficient.
In order to calculate:

parseFloat( 0.5 * document.forms[0].boxTwo.value )

The engine first converts the element value to a number so
it can be multiplied by 0.5, which yields another number.

Then, because parseFloat requires a string as an argument,
that resulting number has to be converted to a string.

Finally, parseFloat converts it back to a number again.
 
D

Dr John Stockton

JRS: In article <[email protected]>, seen in
news:comp.lang.javascript said:
I cant seem to calculate the sum with:
document.forms[0].boxOne.value + 0.5*document.forms[0].boxTwo.value

If boxOne contains "1", and boxTwo "3" then the line above prints 11.5..
And thats not the sum..

Can anyone help?


Anyone who has read the newsgroup FAQ, as posted on Mon & Fri each week,
will be able to do so; try it.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top