-1

I have an API call going on which returns the venue_capacity of a soccer team as a number without thousand separator. I would like to print this as string and thousand separator included.

My idea is to run the function after I have the data from the API to manipulate the variable venue_capacity accordingly.

This is my current attempt (from this thread: How to print a number with commas as thousands separators in JavaScript) which returns the figure without a separator:

  $.ajax({
    method: "GET",
    async: "True",
    dataType: "json",
    url: "https://cors-anywhere.herokuapp.com/https://www.api-football.com/demo/api/v2/teams/team/" + team_id,
    success: function(response) {
      var team_info = response;
      console.log(team_info);

      team = team_info.api.teams[0].name;
      founded = team_info.api.teams[0].founded;
      venue_capacity = team_info.api.teams[0].venue_capacity;

      function numberWithCommas(venue_capacity) {
        return venue_capacity.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ".");
      }

      $("#selectedClub").html(team);
      $("#founded").html(founded);
      $("#venue_capacity").html(venue_capacity);

    }
JSRB
  • 2,492
  • 1
  • 17
  • 48
  • Well, you shoved a `numberWithCommas` function in your success call but where do you actually use it? Seems like all you need is `venue_capacity.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ".");` and not the function wrapper – j08691 Oct 11 '19 at 18:53
  • I don't necessarily agree with the statement that the function you've copied and pasted from the linked thread "*returns the figure without a separator*" - you've declared the function, but haven't referenced it anywhere. – esqew Oct 11 '19 at 18:54

2 Answers2

2

You don't have to mess around with declaring functions in the scope of $.ajax - just perform the translation in one shot:

venue_capacity = team_info.api.teams[0].venue_capacity.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ".");
esqew
  • 42,425
  • 27
  • 92
  • 132
2

Try to use this function instead:

function formatWithCommat(x){
  return x.toLocaleString('en-GB');
}

You can find here more information about it https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString