user13286
user13286

Reputation: 3075

Calculate the sum of multiple currency formatted elements

I am trying to create a sub-total based on a series of currency formatted numbers but am struggling converting the numbers back to integers so that they can be added. Here's what I have tried:

$(function() {
  var totals = $('.price');

  var sum = 0;
  for (var i = 0; i < totals.length; i++) {
    //strip out dollar signs and commas
    $(totals[i].text()).replace(/[^\d.]/g, '');

    //convert string to integer
    var ct = parseFloat($(totals[i].text()));
    sum += ct;
  }

  console.log(sum);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="price">$195,000.20</div>
<div class="price">$21,404.00</div>
<div class="price">$7,000.00</div>
<div class="price">$450.00</div>

Upvotes: 0

Views: 1767

Answers (1)

Paul Roub
Paul Roub

Reputation: 36448

replace() doesn't modify the string passed in (and it couldn't here anyway, since it's the result of a function). It just returns the modified value.

Save the result of replace(), and sum based on that:

$(function() {
  var totals = $('.price');

  var sum = 0;
  for (var i = 0; i < totals.length; i++) {
    //strip out dollar signs and commas
    var v = $(totals[i]).text().replace(/[^\d.]/g, '');

    //convert string to integer
    var ct = parseFloat(v);
    sum += ct;
  }

  console.log(sum);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="price">$195,000.20</div>
<div class="price">$21,404.00</div>
<div class="price">$7,000.00</div>
<div class="price">$450.00</div>

Also: note the typo -- you want $(totals[i]).text(), not $(totals[i].text())

Upvotes: 3

Related Questions