0

I'm having problems with my (javascript) API. When I use the coinmarketcap API (https://api.coinmarketcap.com/v1/ticker). As for "max_supply" for bitcoin, it gives me "16865112.0" in text. This is a problem. I want to automatically put comma's in the number like 16,865,112.0.

If the data id is for example ethereum (it doesnt have a max supply) it gives me ∞. That works.

Original:

$.get("https://api.coinmarketcap.com/v1/ticker/", function(data, status) {
  for (var i = 0; i < data.length - 1; i++) {
    if (data[i].id == "bitcoin") {
      $("#max_supply").html(data[i].max_supply == null ? '∞' : data[i].max_supply);
    }
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="max_supply"></div>

This gives me an output of "21000000.0"

This is what i got so far

$.get("https://api.coinmarketcap.com/v1/ticker/", function(data, status) {
  for (var i = 0; i < data.length - 1; i++) {
    if (data[i].id == "bitcoin") {
      $("#max_supply").html(Number(data[i].max_supply).toLocaleString('en-US') == null ? '∞' : data[i].max_supply.toLocaleString('en-US'));
    }
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="max_supply"></div>

This doesn't give me an output.

Any suggestions?

Andrew Lohr
  • 5,380
  • 1
  • 26
  • 38
hypern00b
  • 53
  • 1
  • 7

1 Answers1

1

First off you should take off the -1 in your for loop, or you will be missing the last item.

The ternary maxSupply = maxSupply == null ? '∞' : numberWithCommas(maxSupply) below says if max supply value is null (for the current coin from the JSON) then set maxSupply to else set maxSupply var to numberWithCommas(maxSupply)

I got the numberWithCommas(...) function from https://stackoverflow.com/a/2901298/1309377 to help format the number with commas like you asked for.

I also switched to .append() instead of .html() otherwise you will just be writing over yourself.

$.get("https://api.coinmarketcap.com/v1/ticker/", function(data, status) {

  for (var i = 0; i < data.length; i++) {
    var coin = data[i].id;
    var maxSupply = data[i].max_supply;
    maxSupply = maxSupply == null ? '∞' : numberWithCommas(maxSupply)
    $("#max_supply").append(coin + ": " + maxSupply + "<br/>");
  }

});

function numberWithCommas(x){
  return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span>Max Supply</span>
<div id="max_supply"></div>
Andrew Lohr
  • 5,380
  • 1
  • 26
  • 38