如何在这段JavaScript函数代码中实现计算结果保留两位小数
解决方案
你可以使用JavaScript内置的toFixed(2)方法处理计算结果,就能实现保留两位小数的需求。建议额外把从DOM读取的输入值先转成数字类型,避免隐式类型转换导致的计算异常,修改后的代码如下:
function calculateTotal() { // 读取输入值并转为数字,非法输入默认按0处理 const unitPrice = Number(document.getElementById("Unit1").value) || 0; const quantity = Number(document.getElementById("quantity1").value) || 0; const total = unitPrice * quantity; // 保留两位小数后赋值给结果输入框 document.getElementById("Total1").value = total.toFixed(2); }
补充说明
- 如果对四舍五入精度要求高,可以用
Math.round先处理避免浮点数精度误差,替换赋值语句为:document.getElementById("Total1").value = (Math.round(total * 100) / 100).toFixed(2) - 如果你的业务场景不需要补末尾的0,比如10要显示为10而不是10.00,可以把
toFixed(2)换成parseFloat(total.toFixed(2))
内容的提问来源于stack exchange,提问作者Josh
相关产品推荐
相关产品推荐

