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);
1
  • 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. Commented Dec 7, 2009 at 1:11

6 Answers 6

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.

Sign up to request clarification or add additional context in comments.

4 Comments

It's a currency so I need it to have 2 decimal places precision.
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.
holding off until the end did the trick. I shouldn't have to initialize the value, correct?
Yes, or the results are undefined. In FF3.5, where I tried, I got "NaN" as the result if I did not initialize it.
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

2 Comments

it still returns a string like 02.3402220.000
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());
3
var totals

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

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

possibly use Math.round, floor or ceil

Comments

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);

Comments

2

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

Comments

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);
  };

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.