Link to home
Start Free TrialLog in
Avatar of djfenom
djfenom

asked on

Calculations in Jquery

Hi, I'm trying to add up several numbers using Jquery, I'm using the following script:

tot = parseFloat($(".subtotal").text());
del = parseFloat('7.50');
$(".total").text(parseFloat(tot + del).toFixed(2));

Basically I'm adding a total to a delivery rate to give a final total.

.subtotal is just a span <span class="subtotal">123</span> and then there is another span for .total which gets updated to correct amount.

This works fine until I get a subtotal of more than 1000 and then it rounds the number down to 1??

Can anyone shed any light?

Thanks

Chris
Avatar of Kiran Sonawane
Kiran Sonawane
Flag of India image

I tried this. Nothing is wrong

http://jsfiddle.net/xAqA7/
Avatar of djfenom
djfenom

ASKER

The total span is pre-populated with a value from the database.

e.g. the total starts as 1,440.00, but when the script has done its thing it is turned it into 1.00
ASKER CERTIFIED SOLUTION
Avatar of hielo
hielo
Flag of Wallis and Futuna image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Yes. @hielo answer is correct. You need to remove all comma (,) from subtotal in order to convert it into float.
Avatar of djfenom

ASKER

Ahh cool, that works, any way of getting the comma back in after it's done the calculation?
try:
$(".total").text( String(parseFloat(tot + del).toFixed(2)).replace(/(\d)(?=(\d{3})+(\.\d+)?$)/g,"$1,") );

Open in new window

Avatar of djfenom

ASKER

Yay, great, thanks!