Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding floats with javascript

I'm using jQuery, and I want to sum up the values in my table column, everything seems to work fine, but my value is returned a string with all the values added like: 123.5013.0012.35

How can I sum these properly?

var totals

$(".add").each(function(i) {
  totals += parseFloat($(this).text()).toFixed(2);
});

console.log(totals);
like image 583
JP Silvashy Avatar asked Dec 07 '09 00:12

JP Silvashy


1 Answers

You've got multiple errors there. One is not initializing totals to something numeric, like 0.0. The second is not realizing that .toFixed() returns a string. Javascript is concatenating the strings together, rather than adding numbers.

Basically the same question has been asked before as javascript-why-does-this-produce-and-ugly-string-i-would-like-currency and answers there should solve this for you.

like image 87
Peter Hansen Avatar answered Oct 20 '22 05:10

Peter Hansen