10

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);
JP Silvashy
  • 46,977
  • 48
  • 149
  • 227
  • 2
    Dude. Why are you using `toFixed` before you've got the total? That turns it into a string, and then they're being appended. Your output should have clued you into that. Secondly, assuming it *did* work as you thought (stays as a float), you'd be lopping off precision before you got your total. – mpen Dec 07 '09 at 01:11

6 Answers6

16

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.

Community
  • 1
  • 1
Peter Hansen
  • 21,046
  • 5
  • 50
  • 72
  • It's a currency so I need it to have 2 decimal places precision. – JP Silvashy Dec 07 '09 at 00:44
  • 1
    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 Dec 07 '09 at 00:56
  • holding off until the end did the trick. I shouldn't have to initialize the value, correct? – JP Silvashy Dec 07 '09 at 01:14
  • 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 Dec 07 '09 at 01:19
5

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

Community
  • 1
  • 1
Marius
  • 57,995
  • 32
  • 132
  • 151
  • it still returns a string like `02.3402220.000` – JP Silvashy Dec 07 '09 at 00:46
  • This worked for me, I was storing the float in an object, somehow it kept being treated as a string, so I was explicit: `[-] total += parseFloat($(this).text());` [+] `total = parseFloat(total) + parseFloat($(this).text());` – roberthuttinger Dec 13 '12 at 14:19
3
var totals

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

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

possibly use Math.round, floor or ceil

just somebody
  • 18,602
  • 6
  • 51
  • 60
3

Simple try this . its works for me.

    var totals= 0;
    $(".add").each(function() {
        if (jQuery(this).val() != '')
            totals= Number(totals) + Number(jQuery(this).val()); 
    });
   console.log(totals);
Maulik Kanani
  • 642
  • 6
  • 22
2

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

Shawn
  • 19,465
  • 20
  • 98
  • 152
2
  function update_total() {
    var total = 0.0;
    $('.invoice_service_price').each(function(index){
      var val=parseFloat($(this).html().trim());
      if(!isNaN(val)) total += val;
    });
    alert("total="+total);
  };
Aivils
  • 21
  • 1