0

Could you please help me? I want to show data from API and format it to currency format.

See the code below, It's already can show the data, but can not format it. For example: if the data show 100000000, I want to format it to IDR100.000.000 IDR= Indonesian Rupiah.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
  var settings = {
    "async": true,
    "crossDomain": true,
    "url": "https://indodax.com/api/summaries",
    "method": "GET"
  }

  $.ajax(settings).done(function(response) {
    console.log(response);

    var content = response.tickers.btc_idr.last;
    $("#harga_bitcoin").append(content);

    var content = response.tickers.btc_idr.buy;
    $("#harga_beli_bitcoin").append(content);

    var content = response.tickers.btc_idr.sell;
    $("#harga_jual_bitcoin").append(content);

    var content = response.tickers.btc_idr.high;
    $("#harga_bitcoin_tertinggi").append(content);

    var content = response.tickers.btc_idr.low;
    $("#harga_bitcoin_terendah").append(content);

  });
</script>

<strong>Harga Bitcoin Hari Ini</strong>: <span style="color: blue;" id="harga_bitcoin">Rp</span><br/>
<strong>Harga Beli Bitcoin</strong>: <span style="color: green;" id="harga_beli_bitcoin">Rp</span><br/>
<strong>Harga Jual Bitcoin</strong>: <span style="color: red;" id="harga_jual_bitcoin">Rp</span><br/>
<strong>Harga Bitcoin Tertinggi 24H</strong>: <span style="color: green;" id="harga_bitcoin_tertinggi">Rp</span><br/>
<strong>Harga Bitcoin Terendah 24H</strong>: <span style="color: red;" id="harga_bitcoin_terendah">Rp</span>

I expect that you guys can help me clearly (what should I add into which line or this or that), because I'm newbie into coding. Thank you in advance.

CodeIt
  • 3,492
  • 3
  • 26
  • 37
Andrea
  • 1
  • 1
  • Possible duplicate of [this](https://stackoverflow.com/questions/149055/how-can-i-format-numbers-as-currency-string-in-javascript) SO question. – Jeroen Heier Jul 20 '19 at 10:37

1 Answers1

0

Use a custom function like this:

function formatMoney(number, decPlaces, decSep, thouSep) {
    decPlaces = isNaN(decPlaces = Math.abs(decPlaces)) ? 2 : decPlaces,
    decSep = typeof decSep === "undefined" ? "." : decSep;
    thouSep = typeof thouSep === "undefined" ? "," : thouSep;
    var sign = number < 0 ? "-" : "";
    var i = String(parseInt(number = Math.abs(Number(number) || 0).toFixed(decPlaces)));
    var j = (j = i.length) > 3 ? j % 3 : 0;

    return sign +
    (j ? i.substr(0, j) + thouSep : "") +
    i.substr(j).replace(/(\decSep{3})(?=\decSep)/g, "$1" + thouSep) +
    (decPlaces ? decSep + Math.abs(number - i).toFixed(decPlaces).slice(2) : "");
}

And then:

$("#harga_bitcoin").append('IDR'+formatMoney(content, 0, '', '.'));

Reference: How can I format numbers as currency string in JavaScript?

François Huppé
  • 2,006
  • 1
  • 6
  • 15