简体   繁体   中英

JavaScript limit output decimal places

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>

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM