2015-08-28 87 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