views:

225

answers:

4

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);
+1  A: 

Here is a working version (tested in firefox 3.5):

<!DOCTYPE html>
<html>
<head>
    <title>Sum of nubers</title>

    <script src="jquery.js" type="text/javascript"></script>
    <script type="text/javascript">

     $(function(){
      var total = 0;
      $(".add").each(function(){
       total += parseFloat($(this).text());
      });
      alert(total.toFixed(2));
     });
    </script>
</head>
<body>
<div class="add">23.4567</div>
<div class="add">98.7654</div>
</body>
</html>

That is just one of the many ways to do it. Have a look at this question for several other methods:

How to convert strings to floats

Marius
it still returns a string like `02.3402220.000`
Joseph Silvashy
+1  A: 

Looks like it's doing a string add. Try setting var totals = 0;

Shawn Simon
I still get `02.3402220.000`
Joseph Silvashy
+2  A: 

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.

Peter Hansen
It's a currency so I need it to have 2 decimal places precision.
Joseph Silvashy
If you just want the final output to have that precision, hold off calling toFixed(2) until the end. Then everything up to that point is adding numbers, not strings. If you are concerned about the intermediate calculations, you've got a couple of things to think about. If this is a "toy" application, use parseFloat() on the output of toFixed() to make sure it's a number again, then call toFixed() again at the end. If this is a "real" application, you probably shouldn't be using floating point values for currency.
Peter Hansen
holding off until the end did the trick. I shouldn't have to initialize the value, correct?
Joseph Silvashy
Yes, or the results are undefined. In FF3.5, where I tried, I got "NaN" as the result if I did not initialize it.
Peter Hansen
+1  A: 
var totals

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

console.log(totals.toFixed(2));

possibly use Math.round, floor or ceil

just somebody