我知道這可能是一個重複的問題,但我一直在尋找年齡,無法弄清楚爲什麼這不起作用。JavaScript計算輸入字段值並顯示2位小數精度
我有3個輸入字段,小計,增值稅和總計:我希望能夠填寫增值稅和總值inpur字段值有小值時輸入值,並顯示2個十進制palces後。所以:
4將4.00 4.5將輸入字段4.50
HTML代碼:
<input name="subtotal" id="subtotal" type="number" maxlength="20" min="0" placeholder="00.00" onchange="vatCalculation();" />
<input name="vat" id="vat" type="number" maxlength="20" min="0" placeholder="00.00" readonly="true" />
<input name="total" id="total" type="number" maxlength="20" min="0" placeholder="00.00" readonly="true" />
和JavaScript代碼,我目前所面對的是:
function vatCalculation() {
var subtotal = document.getElementById('subtotal').value;
var vat = parseFloat(parseFloat(subtotal) * parseFloat(0.2)).toFixed(2);
var total = parseFloat(parseFloat(subtotal) + parseFloat(vat)).toFixed(2);
document.getElementById('vat').value = vat;
document.getElementById('total').value = total;
}
我不能看到我要去哪裏錯了。當我在「小計」輸入字段中輸入10時,「增值稅」和「總計」字段將變爲2和12.但我希望它們顯示2.00和12.00。下面截圖:
SOLUTION:
當使用Firefox類型的輸入字段= 「數量」 不似乎與JavaScript計算工作。解決方法是將其更改爲類型=「文本」像J Santosh一樣,如下所述,它的工作原理。
[格式號碼始終顯示2位小數(可能重複http://stackoverflow.com/questions/6134039/format-number-to-always-show-2 -decimal-places) – stevenw00