如何解决JavaScript限制输出小数位
我一直试图将'priceChangePercent'的输出数据限制为两位小数,但似乎无法使其正常工作。谁能指出我正确的方向?
功能
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)在转换为数字后会成功完成
您可能也想添加货币吗?
我也添加了颜色类别。
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>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。