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(parseFloa t(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
tot = parseFloat($(".subtotal").
del = parseFloat('7.50');
$(".total").text(parseFloa
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
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
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
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
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Yes. @hielo answer is correct. You need to remove all comma (,) from subtotal in order to convert it into float.
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,") );
ASKER
Yay, great, thanks!
http://jsfiddle.net/xAqA7/