1

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 normally I use toLocaleString() but it is marked as text and it doesnt work.

$.get("https://api.coinmarketcap.com/v1/ticker/", function(data, status) {
  for (var i = 0; i < data.length - 1; i++) {
    if (data[i].id == "bitcoin") {
     $("#total_supply").html(data[i].total_supply.toLocaleString());  
     }
  }
}); 

Any suggestions?

hypern00b
  • 53
  • 1
  • 7
  • 1
    You may want to have a look at this answer: https://stackoverflow.com/questions/149055/how-can-i-format-numbers-as-dollars-currency-string-in-javascript – Varinder Feb 14 '18 at 21:07

2 Answers2

2

You can still do it, just first convert string to number.

var value = "16865112.0";
value = +value; // convert to number
var fV = Number(value).toLocaleString();
console.log(fV);
void
  • 36,090
  • 8
  • 62
  • 107
2

You are calling Number.toLocaleString on String. You need to convert it to Number first by calling parseInt or Number() constructor (you can change your current locale too).

$.get("https://api.coinmarketcap.com/v1/ticker/", function(data, status) {
  for (var i = 0; i < data.length - 1; i++) {
    if (data[i].id == "bitcoin") {
     $("#total_supply").html(Number(data[i].total_supply).toLocaleString('en-US'));  
     }
  }
}); 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="total_supply"></div>
  • Thanks it worked, but when I try it on this: ' `$("#max_supply").html(data[i].max_supply == null ? '∞' : data[i].max_supply);` -> `$("#max_supply").html(Number(data[i].max_supply).toLocaleString('en-US') == null ? '∞' : data[i].max_supply.toLocaleString('en-US'));` It doesnt work what did I do wrong? – hypern00b Feb 14 '18 at 21:52
  • @hypern00b I believe you converted wrong part, try it like this: `$("#max_supply").html(data[i].max_supply.toLocaleString('en-US') == null ? '∞' : Number(data[i].max_supply).toLocaleString('en-US'));` – Jiří Šimeček Feb 15 '18 at 20:46