Hello and welcome to our community! Is this your first visit?
Enjoy an ad free experience by logging in. Not a member yet? Register.

1. ## js math problem?

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

• If either of the operands of the + operator is a sting, it will perform concatenation instead of addition. And I believe
Code:
`temp = t.value * tx.value / 100 + t.value + ot.value;`
will be a string.

• 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

• 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

• 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...

• kool!
that fixes my problem:-)

thanks!
-ken

•

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•