using num.toFixed();

using num.toFixed();

本文关键字:toFixed num using      更新时间:2023-09-26

在下面的函数中,我将在哪里包括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" />
theForm.total.value = total.toFixed(2);
theForm.GrandTotal.value = (total + (total*0.18)).toFixed(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.toFixed(2);
    theForm.GrandTotal.value = (total + (total*0.18)).toFixed(2);
}

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`)