2015-08-28 86 views
1

我知道這可能是一個重複的問題,但我一直在尋找年齡,無法弄清楚爲什麼這不起作用。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。下面截圖:

enter image description here

SOLUTION:

當使用Firefox類型的輸入字段= 「數量」 不似乎與JavaScript計算工作。解決方法是將其更改爲類型=「文本」像J Santosh一樣,如下所述,它的工作原理。

+1

[格式號碼始終顯示2位小數(可能重複http://stackoverflow.com/questions/6134039/format-number-to-always-show-2 -decimal-places) – stevenw00

回答

5

發現的問題。它與<input type='number'>將其更改爲<input type='text'>

Working Fiddle

輸入類型不被接受小數

Reference -1

Reference-2

+0

完美J桑託什...所以很煩人,它是那麼小......那麼你會知道爲什麼它不起作用時,類型=「數字」? – Harnamc

+0

@Harnamc這是因爲瀏覽器會自動將該值轉換爲數字,並將其顯示爲字符串格式。 – Buzinas

1

這是你想要的嗎?如果是這樣,你是非常接近。你只需要添加

document.getElementById('subtotal').value = parseFloat(subtotal).toFixed(2); 

以及你的代碼。

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('subtotal').value = parseFloat(subtotal).toFixed(2); 
 
document.getElementById('vat').value = vat; 
 
document.getElementById('total').value = total; 
 
}
<input name="subtotal" id="subtotal" type="text" maxlength="20" min="0" placeholder="00.00" onchange="vatCalculation();" /> 
 

 
<input name="vat" id="vat" type="text" maxlength="20" min="0" placeholder="00.00" readonly="true" /> 
 

 
<input name="total" id="total" type="text" maxlength="20" min="0" placeholder="00.00" readonly="true" />

+0

它不適用於Firefox! – Buzinas

+0

Buzinas你是對的,在Chrome瀏覽器中工作正常,但在Firefox中使用type =「number」時不起作用...將使用J Santosh的答案並將輸入更改爲type =「text」並使用RegEx將其限制爲只有數字。 – Harnamc

+0

@mcon - 當你在Firefox中輸入=「text」時,它工作的很好。這是一個瀏覽器問題。感謝您的幫助,以便在小計上添加額外的小數。忘記了:) – Harnamc

0

(2.399).toFixed(2);會給你2.40

但是如果你需要2.39嘗試

parseInt(2.399 * 100)/100