0
可能重複:
JavaScript: formatting number with exactly two decimals
Round up to 2 decimal places in javascript努力的結果四捨五入至小數點後2位
<form name="shippingForm" method="post" action="">
<h2>Product Cost</h2>
<ul>
<li><input type="text" name="YourValue" id="YourValue" value=""/></li>
<li><label>VAT @ 17.5% +</label></li>
<li><input type="text" name="costShipping" id="costShipping" value=""/></li>
<li><label>Currency conversion rate: 1.98</label></li>
<li><div id="totalPrice"></div></li>
<li><input type="button" value="Calculate" name="calculate" id="calculate"/></li>
</ul>
</form>
以上是形式。這是做什麼的,是要求用戶輸入2個值,但第二個值是可選的。然後計算並顯示結果。
<script type="text/javascript">
var button = document.getElementById('calculate');
button.onclick = function() {
var YourValue = parseInt(document.getElementById('YourValue').value);
var LocalTax = 17.5/100 * YourValue;
var costShipping = parseInt(document.getElementById('costShipping').value);
var convCurrency = 1.98;
var totalPrice = document.getElementById('totalPrice');
if (document.getElementById('costShipping').value === "") {
totalPrice.innerHTML = "= $"+(YourValue + LocalTax + 0) * convCurrency;
}
else {
totalPrice.innerHTML = "= $"+(YourValue + LocalTax + costShipping) * convCurrency;
}
};
</script>
什麼,我想這樣做是對totalPrice結果四捨五入到2位小數