2014-09-04 80 views
0

我以前用類似的方式發佈了一個代碼,我仍然有問題。這次我得到100.0712.5當我把10作爲帳單,7爲銷售稅和25爲小費。我對Javascript編碼真的很陌生,而且我幾乎花了數小時試圖弄清楚我需要幫助。銷售和小費計算器

<html> 
<head> 

<script type="text/javascript"> 
function applyTax(){ 


    var inputAmount = document.getElementById('dollars').value; 
    var salesTax = document.getElementById('tax').value; 
    var tip = document.getElementById('tip').value; 
    var totalAmount = (salesTax/100) + (inputAmount); 
    var tipprcnt = (tip/100) * (inputAmount); 
    var Grandtotal = (inputAmount + (totalAmount*1) + (tipprcnt*1)); 

    //document.getElementById('requestedAmount').innerHTML = tipprcnt; 
    //document.getElementById('requestedTax').innerHTML = totalAmount; 
    document.getElementById('requestedGrand').innerHTML = Grandtotal; 
} 

</script> 

</head> 
<body> 

<h1>Sales Tax + Tip Calculator</h1> 
<p>Type in your price (dollar amount). Click the &quot;Calculate&quot; button to receive your total. 
</p> 
<p> 
    What is the bill amount?: $<input type="text" id="dollars" /> <br> 
    What is the sales tax?:<input type="text" id="tax" />%<br> 
    how much do you want to tip?:<input type="text" id="tip" />% 
    <input type="button" onclick="applyTax();" value="Calculate" /> 

</p> 
</h2>The Grand Total is:</h2> 
<div id="requestedAmount"> </div> 
<div id="requestedTax"> </div> 
<div id="requestedGrand"> </div> 
<p><a href="http://jasonhuang.myweb.usf.edu/lis4365/index.html">Home</a> 
</body> 
</html> 
+0

你將稅額添加到輸入數量而不是乘以它。 – Barmar 2014-09-04 22:58:38

+0

@Bijan他這樣做是爲了將它從一個字符串轉換爲一個數字,所以'+'會做加法而不是連接。除了需要轉換的是'inputAmount'。 – Barmar 2014-09-04 23:04:19

回答

0
function applyTax(){ 
    var inputAmount = parseFloat(document.getElementById('dollars').value); 
    var salesTax = parseFloat(document.getElementById('tax').value); 
    var tip = parseFloat(document.getElementById('tip').value); 
    var taxprcnt = (salesTax/100) * (inputAmount); 
    var tipprcnt = (tip/100) * (inputAmount); 
    var Grandtotal = inputAmount + taxprcnt + tipprcnt; 

    document.getElementById('requestedGrand').innerHTML = Grandtotal.toFixed(2); // Round to 2 decimals 
} 
  1. 您應該使用parseFloat()的輸入轉換爲數字。
  2. 您需要將輸入金額乘以稅率百分比,而不是將它們相加。
  3. 您應該捨棄最終結果,因爲人們不想看到分數便士。

DEMO

當我輸入$ 10,7%的稅,25%的小費,總爲$ 13,20。

0

通過每個輸入使用Number(input.value)將字符串值轉換爲數字。如果需要,您可以使用parseInt()parseFloat而不是​​。第一個轉換爲整數,第二個轉換爲帶有小數點的數字。

順便說一句忘記()*1的過度使用,這是其他人只是噪音...

你的變量名是混亂的,但我想你想是這樣的:

var amountInput = document.getElementById("dollars"); 
var taxInput = document.getElementById("tax"); 
var tipInput = document.getElementById("tip"); 

var amount = Number(amountInput.value); 
var taxPercent = Number(taxInput.value); 
var tipPercent = Number(tipInput.value); 

var grandTotal = Math.round(amount * (100 + taxPercent + tipPercent))/100; 

var grandTotalOutput = document.getElementById("requestedGrand"); 
grandTotalOutput.innerHTML = grandTotal;