PDA

View Full Version : js math problem?

angst
12-20-2005, 05:02 PM
hi,
I'm trying to add some numbers together using javascript,
but instead of the numbers being added together, it's just putting the numbers side by side.
example

1 + 25 gives me 125.

my code:

var tx=document.forms[0].tax;
var ot=document.forms[0]. order_total
var q=document.forms[0].qty;
var c=document.forms[0].price_each;
var t=document.forms[0].amount;

if (isNaN(q.value)||isNaN(c.value)){
q.value=q.value.replace(/\D/g,'');
c.value=c.value.replace(/\D/g,'');
tx.value=tx.value.replace(/\D/g,'');
ot.value=ot.value.replace(/\D/g,'');
t.value=ot.value.replace(/\D/g,'');
}
if (q.value.length>0&&c.value.length>0){
t.value=parseInt(q.value) * parseInt(c.value);
temp = t.value * tx.value / 100 + t.value + ot.value;
ot.value = Math.round(temp*100)/100;
}
}

any ideas what I'm doing wrong here?

-Ken

liorean
12-20-2005, 05:27 PM
If either of the operands of the + operator is a sting, it will perform concatenation instead of addition. And I believe
temp = t.value * tx.value / 100 + t.value + ot.value; will be a string.

angst
12-20-2005, 05:39 PM
umm,
I'm not really sure what you mean,
I'm pretty new to this stuff still, and can't you tell me how I can fix this problem? do they need to be cast as Int's? thats what I would do in ASP or PHP for this kind of problem..?

thanks again,
-ken

angst
12-20-2005, 05:49 PM
ok,
it's adding the numbers together now,
but still wrong,

example:
if I do 1 + 28.75
I get 29, this is very strange, and I have no idea what I'm doing wrong here..

if (q.value.length>0&&c.value.length>0){
t.value=parseInt(q.value) * parseInt(c.value);
temp = t.value * tx.value / 100 + t.value;
ot.value = parseInt(temp) + parseInt(ot.value);
//ot.value = Math.round(temp*100)/100;
}

any help would be greate!

-Ken

Nischumacher
12-20-2005, 05:55 PM
use parseFloat(string)... or Number(string)...

parseInt() returns an integer

parseInt('28.75') = 28
parseFloat('28.75')=28.75
Number('28.75')=28.75

PS : value of an element is a string... it needs to be converted to integer or float according to the requirement...

angst
12-20-2005, 06:02 PM
kool!
that fixes my problem:-)

thanks!
-ken