我正在尝试格式化货币值以仅显示2位小数,并且如果为负则也会更改输出值。目前,输出呈现14个十进制字符,并且关闭$ 0.01!
我有JSFiddle显示输出,描述了我遇到的这两个问题。
javascript非常简单!也许它的简单性是问题的原因。这是脚本:
var accountbalance = 99.99;
var renewalfee = 64.95;
var balanceafterrenewal = (accountbalance - renewalfee);
document.getElementById("remainingBalance").innerHTML = balanceafterrenewal;
呈现输出的HTML代码如下:
<div class="remainingbalancelabel">Remaining Balance Rendering Output</div>
$<span id="remainingBalance"></span>
</div>
我将不胜感激:
我会提前感谢你! :)
答案 0 :(得分:1)
使用.toFixed
设置为一定的小数位数:
document.getElementById("remainingBalance").innerHTML = balanceafterrenewal.toFixed(2);
分配给元素&#39; .style.color
以更改其颜色:
const accountbalance = 99.99;
const renewalfee = 100;
const balanceafterrenewal = (accountbalance - renewalfee);
document.getElementById("remainingBalance").innerHTML = balanceafterrenewal.toFixed(2);
if (balanceafterrenewal < 0) document.getElementById("remainingBalance").style.color = 'red';
&#13;
<span id="remainingBalance"></span>
&#13;
答案 1 :(得分:1)