Javascript 使用num.toFixed();
在下面的函数中,我将在哪里包括num.toFixed(2);是否将“总计”的估价师显示为小数点后2位(价格) 这是输出:Javascript 使用num.toFixed();,javascript,Javascript,在下面的函数中,我将在哪里包括num.toFixed(2);是否将“总计”的估价师显示为小数点后2位(价格) 这是输出: <input type="button" name="CheckValue" value = "Calculate cost" onclick="calculate_total(this.form.id)" /> Total: <input type="text" name="total" id="total" size="10" re
<input type="button" name="CheckValue" value = "Calculate cost" onclick="calculate_total(this.form.id)" />
Total: <input type="text" name="total" id="total" size="10" readonly="readonly" />
总数:
在num.toFixed()
中,num
是希望影响的实际数值表达式。对该表达式运行toFixed
函数
因此,您可以将其应用于total+(total*0.18)
:
但是,不要。不要在这里截断您的值,否则会通过显著限制精度而在代码中引入潜在的舍入错误
这可能是经过深思熟虑的(取决于您希望在计算中处理次便士值的方式),如果是,则您还应将其应用于正常的总
值:
theForm.total.value = total.toFixed(2);
否则,请在输出值时应用此格式!i、 e.其他地方:
alert(theForm.GrandTotal.value.toFixed(2));
// (or something other than `alert`)
我会将其改为两位,以确保两个数字的格式均为两位小数:
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);
}
在哪里输出它?是的。tofixed(2);四舍五入到小数点后两位?@Joel:是的。如果你连它的功能都不知道,为什么还要用它?阅读
theForm.total.value = total.toFixed(2);
alert(theForm.GrandTotal.value.toFixed(2));
// (or something other than `alert`)
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);
}