Search code examples
jqueryarraysoperations

currency extraction jQuery


Clicking on any currency (e.g. $44,721.90) should extract by itself and return $0.

Currently is returning $NaN. I'm using ES6 Intl.NumberFormat("en-US") to give currency format to the numbers.

var name1 = {
  name: "John",
  money: 44721.90
};
var name2 = {
  name: "Mayer",
  money: 16715.79
};

var names = [name1, name2];

function show() {
  var numFormat = new Intl.NumberFormat("en-US");
  for (var i = 0; i < names.length; i++) {
    $(".money").append('<div class="extract' + [i] + '"><span class="name">' + names[i].name + ' </span><span class="budget"> $' + numFormat.format(names[i].money) + '</span></div><br>');
  }
}

show();

function extraction() {
  for (var i = 0; i < names.length; i++) {
    //var text = $(".coin" + [i]).text();
    $(".extract" + [i]).click(function() {
      var currentCoin = $(this).find('.budget');
      var difference = $(this).find('.budget') - $(this).find('.budget');
      //var difference = (Number($(currentCoin).text().replace('$','')) - Number($(currentCoin).text().replace('$','')));
      $(currentCoin).html('$' + difference);
    })
  }
}

extraction();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="money"></div>


Solution

  • In var difference, you are selecting a string with a $ and ,, which isn't valid to have in a number. You need to take those out of the string, something like this for that line:

    var difference = parseFloat($(this).find('.budget').text().replace(',','').replace('$','')) - parseFloat($(this).find('.budget').text().replace(',','').replace('$',''));
    

    See this jsfiddle.

    Edit:

    In case you decide to use something other than dollar signs you can use a regex /[0-9\.]+/g to match instead. I think this solution is much better actually. Here's a jsfiddle, I replaced the former change with a getFloat() function. This will work for any kind of currency.