可能重复:
JavaScript: formatting number with exactly two decimals
Round up to 2 decimal places in javascript
<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位小数