javascript - 如何使用固定四舍五入到小数点后两位(2)
问题描述
我的一部分代码处理数学和求和。大多数方程等于小数点后三位,但我想将其固定为 2。我知道使用 tofixed(2),但我将函数放在哪里似乎并不重要,数字保持为小数点后三位。我确定我犯了一些愚蠢的错误
<script language="JavaScript">
function SetFoodItems(amount) {
// returns the amount in the .99 format
return (amount == Math.floor(amount)) ? amount + '.00' : ((amount * 10
== Math.floor(amount * 10)) ? amount + '0' : amount);
}
function SelectFoodItems(form) {
var UpdateCosts = (form.quantity.value - 0) * (form.unitcost.value -
0) + (form.quantity1.value - 0) * (form.unitcost1.value - 0)
(form.quantity2.value - 0) * (form.unitcost2.value - 0) +
(form.quantity3.value - 0) * (form.unitcost3.value - 0).toFixed(2);
UpdateCosts = Math.floor((subtotal * 1000) / 1000).toFixed(2);
form.subtotal.value = ('$' + cent(subtotal));
var tax = (UpdateCosts / 100 * (form.rate.value - 0).toFixed(2);
tax = Math.floor(tax * 1000) / 1000;
form.tax.value = '$' + cent(tax);
total = UpdateCosts + tax;
total = Math.floor((total * 1000) / 1000);
form.total.value = ('$' + cent(total)).toFixed(2);
}
</script>
解决方案
你的最后一行:
form.total.value = ('$' + cent(total)).toFixed(2);
应调整为:
form.total.value = '$' + cent(total).toFixed(2);
该('$' + cent(total))
位将总数转换为没有 toFixed 方法的字符串。
但是, toFixed 不会对数字进行四舍五入,它会截断(截断数字,2.005 将变为“2.00”而不是“2.01”)并断言新字符串中将恰好有 n 个数字。在进一步的数字运算中使用结果可能会导致问题(将数字添加到字符串将追加)。
如果这是您真正想要的,您可以使用带有乘法和除法的 Math.round 函数来实现舍入。
您可以在此处查看如何实现这一点:如何在 Javascript 中舍入到小数点后 1 位?
或者作为一个函数,您可以直接在代码中使用:
function roundMoney(dollarAmount) {
var cents = dollarAmount * 100;
return Math.round(cents) / 100;
}
当最终在 form.value.total 中显示值时,您仍然需要 toFixed 以保持最后两位小数
推荐阅读
- r - 根据条件删除R中矩阵的行
- class - 使用 Jenkins 共享库作为类
- android - Android工作室中的图像排序
- c# - wpf小吃栏不显示消息
- python - 如何在 keras python 中构建一维卷积神经网络?
- vue.js - Vue.js v-bind:值到空对象
- java - 来自 n 个列表的笛卡尔积
- vue.js - 继承父上下文的 vuejs 组件
- selenium-webdriver - 无法使用 Serenity 在 BrowserStack 上进行测试并在本地计算机上启动 WebTest
- android - 如何在没有 WallpaperManager 的情况下设置墙纸