-1

I've been trying to limit the output data for 'priceChangePercent' to 2 decimal places but can't seem to get it working. Can anyone point me in the right direction?

Function

async function getPriceBTCUSDT() {
  const response = await fetch("https://api.binance.com/api/v3/ticker/24hr?symbol=BTCUSDT");
  const data = await response.json();
  const {
    prevClosePrice,
    priceChangePercent
  } = data;
  if (priceChangePercent > 0) {
    document.getElementById('24hr-btcusdt').style.color = 'green'
  }

  document.getElementById('price-btcusdt').textContent = prevClosePrice;
  document.getElementById('24hr-btcusdt').textContent = priceChangePercent + "%";

}

getPriceBTCUSDT();

setInterval(getPriceBTCUSDT, 3000);
<span id="price-btcusdt"></span>
<span id="24hr-btcusdt"></span>
Aluan Haddad
  • 29,886
  • 8
  • 72
  • 84
Ryan Brown
  • 31
  • 7
  • 1
    var num = 5.56789; var n = num.toFixed(2); – jAdex Aug 13 '20 at 12:04
  • 2
    Does this answer your question? [Format number to always show 2 decimal places](https://stackoverflow.com/questions/6134039/format-number-to-always-show-2-decimal-places) – Smile Aug 13 '20 at 12:11

1 Answers1

2

toFixed(2) will do the trick after you cast to number

You may want to add the currency too?

I added colour classes too.

async function getPriceBTCUSDT() {
  const response = await fetch("https://api.binance.com/api/v3/ticker/24hr?symbol=BTCUSDT");
  const data = await response.json();
  const {
    prevClosePrice,
    priceChangePercent
  } = data; 
  const pctSpan = document.getElementById('24hr-btcusdt');
  const priceSpan = document.getElementById('price-btcusdt');
  pctSpan.className = priceChangePercent >= 0 ? "green" : "red";
  pctSpan.textContent = priceChangePercent + "%";
  priceSpan.textContent = "$" + Number(prevClosePrice).toFixed(2);
  

}

getPriceBTCUSDT();

setInterval(getPriceBTCUSDT, 3000);
.red {
  color: red;
}

.green {
  color: green;
}
<span id="price-btcusdt"></span>
<span id="24hr-btcusdt"></span>
mplungjan
  • 169,008
  • 28
  • 173
  • 236