2013-02-25 52 views
0

在下面的函數中,我將包含num.toFixed(2);使「總計」的估價師顯示爲小數點後兩位(價格)?using num.toFixed();

function calculate_total(id) { 
    var theForm = document.getElementById(id) 
    total = 0; 
    if (theForm.toyCar.checked) { 
     total += parseFloat(theForm.toyCar.value); 
    } 
    theForm.total.value = total; 
    theForm.GrandTotal.value = total + (total*0.18); 
} 

這是輸出:

<input type="button" name="CheckValue" value = "Calculate cost" onclick="calculate_total(this.form.id)" /> 
&nbsp; 
Total: <input type="text" name="total" id="total" size="10" readonly="readonly" /> 
+1

凡你輸出了嗎? – epascarello 2013-02-25 14:54:42

回答

0
theForm.total.value = total.toFixed(2); 
theForm.GrandTotal.value = (total + (total*0.18)).toFixed(2); 
+0

啊當然!謝啦! – Joel 2013-02-25 14:59:40

-1

num.toFixed()num是實際的數值表達式,希望影響。你運行toFixed函數表達式。

所以,在這裏你可以把它應用到total + (total*0.18)

theForm.GrandTotal.value = (total + (total*0.18)).toFixed(2); 

然而,。不要在此處截斷值,或者在代碼中引入可能的舍入誤差明顯會限制精度的數量

這可能是故意的(這取決於你想在你的計算處理子一分錢值的方式),如果是的話,你也應該把它應用到正常total值:

theForm.total.value = total.toFixed(2); 

否則,在你輸入的值時應用此格式!即,在別處:

alert(theForm.GrandTotal.value.toFixed(2)); 
// (or something other than `alert`) 
+0

does .tofixed(2);四捨五入至小數點後兩位? – Joel 2013-02-25 15:01:33

+0

@Joel:是的。如果你甚至不知道它的作用,爲什麼要使用它?閱讀[文檔](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Number/toFixed)。 – 2013-02-25 15:03:00

+0

Downvote請問什麼原因? – 2013-02-25 15:48:03

0

我要改變它在兩個地方,以確保這兩個數字被格式化爲小數點後兩位:

function calculate_total(id) { 
    var theForm = document.getElementById(id) 
    total = 0; 
    if (theForm.toyCar.checked) { 
     total += parseFloat(theForm.toyCar.value); 
    } 
    theForm.total.value = total.toFixed(2); 
    theForm.GrandTotal.value = (total + (total*0.18)).toFixed(2); 
}