View Full Version : Changin a string variable to a numeric variable

Dieter Rausch
01-08-2004, 08:29 PM
Hi JS coders,

I want to add a value - entered into a hidden text box while the page loads - to another value entered after loading the page and get the sum of the two values.

However, it appears that the first entry is taken as a string variable and concatenated to the latter. For example:

The first entry goes into a hidden field:

<input type="hidden" name="slippage" value="5" id="fldSlippage">

The second entry goes manually after loading into this field:

<input type="text" name="tradeEntry" id="fldEntry">

The two are then added together by calling a function which assigns the hidden field's value to a variable as well as the visible field's value to a separate variable by the following code:

var slipFact=document.getElementById("fldSlippage").value;
var tradeEntry=document.getElementById("fldEntry").value;

Finally, a third variable is calcualted by:

var pointsRisk=(tradeEntry+slipFact);

From the answer obtained it is clear that concatenation takes place instead of addition, i.e.

100+5 yields 1005 instead of 105. However, if I replace the "+" sign with a "-" , then 100-5 yields 95, which is correct.

Now, how do I get JS to do an addition instead of concatenation? So far I could not find an answer in various JS tutorials.


Dieter Rausch
01-08-2004, 08:40 PM
Just as a try, I divided both numbers by 1 and the added them and the answer is then correct.

(100/1 + 5/1)=105. [Division or subrtaction tells JS that we are dealing with numbers and not strings]

But I sure there must be a more efficient way.


01-08-2004, 09:19 PM
var pointsRisk=eval(tradeEntry+slipFact);

01-08-2004, 09:43 PM
Instead of dividing by zero (which is a kluge) eval (which, if you search the forums, is evil), use the functions that are meant to parse numbers from string variables:

var pointsRisk=parseFloat(tradeEntry) + parseFloat(slipFact);

If you're absolutely certain the fields will never contain decimal values, you might use parseInt() instead of parseFloat().

Dieter Rausch
01-08-2004, 10:20 PM
Thanks guys,

I first tried:
var pointsRisk=eval(tradeEntry+slipFact); and still got the wrong answer.

eval(100+slipFact) returned 1005 as the answer, still concatenating. (slipFact=5)

eval(100+5) gave the correct answer of 105. I think this proves that eval is actually evil as I saw mentioned in this forum while doing a search on eval.

Then I changed the coding to parseFloat() and the problem was solved.:thumbsup:

I still have a lot to learn with regard to JS, but with your help I am learning fast.


EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum