我已多次搜索并尝试但仍无法获得。我如何前置" $"并将值四舍五入到最接近的十进制小数。示例:$100.00
<script>
$.get("https://api.coinmarketcap.com/v1/ticker/", function(data, status) {
for (var i = 0; i < data.length - 1; i++) {
if (data[i].id == "unit") {
$("#unit").html(parseFloat(data[i].price_usd) * 500000);
}
}
});
</script>
答案 0 :(得分:2)
使用Number.prototype.toFixed()来生成固定数量的小数,像往常一样连接字符串,因为toFixed返回字符串:
function toCurrency(value = 0, symbol = '$', onEnd = false) {
if (onEnd) {
return Number(value).toFixed(2) + symbol;
}
return symbol + Number(value).toFixed(2);
}
console.log(toCurrency(123.7483));
console.log(toCurrency(123));
console.log(toCurrency(123, ' USD', true));
&#13;