<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 结果四舍五入到小数点后两位