We help IT Professionals succeed at work.

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
Comment
Watch Question

Kiran SonawaneProject Lead
CERTIFIED EXPERT
Top Expert 2011

Commented:
I tried this. Nothing is wrong

http://jsfiddle.net/xAqA7/

Author

Commented:
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
CERTIFIED EXPERT
Expert of the Year 2008
Top Expert 2008
Commented:
try:
tot = parseFloat( $(".subtotal").text().replace(/[^\d\.]/g,'') );
del = parseFloat('7.50');
$(".total").text(parseFloat(tot + del).toFixed(2));

Open in new window

Kiran SonawaneProject Lead
CERTIFIED EXPERT
Top Expert 2011

Commented:
Yes. @hielo answer is correct. You need to remove all comma (,) from subtotal in order to convert it into float.

Author

Commented:
Ahh cool, that works, any way of getting the comma back in after it's done the calculation?
CERTIFIED EXPERT
Expert of the Year 2008
Top Expert 2008

Commented:
try:
$(".total").text( String(parseFloat(tot + del).toFixed(2)).replace(/(\d)(?=(\d{3})+(\.\d+)?$)/g,"$1,") );

Open in new window

Author

Commented:
Yay, great, thanks!

Explore More ContentExplore courses, solutions, and other research materials related to this topic.