0

在下面的函数中,我将在哪里包含 num.toFixed(2); 使“总计”的估价器显示到小数点后 2 位(价格)?

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" />
4

3 回答 3

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);
}
于 2013-02-25T14:57:41.870 回答
0
theForm.total.value = total.toFixed(2);
theForm.GrandTotal.value = (total + (total*0.18)).toFixed(2);
于 2013-02-25T14:55:43.493 回答
-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`)
于 2013-02-25T14:56:14.830 回答