0

我有一些代码涉及我试图只显示两位小数的计算。我正在使用 .toFixed(2),但它仍然无法正常工作。我把它放在正确的位置了吗?

   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';
   }

  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;
    form.subtotal.value = '$' + SetFoodItems(subtotal).toFixed(2);

    var tax = (UpdateCosts / 100 * (form.rate.value - 0).toFixed(2);
    tax = Math.floor(tax * 1000) / 1000;
    form.tax.value = '$' + SetFoodItems(tax);

    total = UpdateCosts + tax;
    total = Math.floor((total * 1000) / 1000);
   form.total.value = '$' + SetFoodItems(total).toFixed(2;
4

1 回答 1

0

如上所述,您的.toFixed()方法返回一个字符串;原因是类型转换。例如,与字符串的加法1 + "0"将 1 转换为字符串,因此您将获得10字符串。如果您在线搜索,您可以找到有关它的更多信息。

现在你知道了;要解决您的问题,您可以使用不同的选项。取决于您希望代码返回的内容,取决于您最喜欢哪一个:

  • parseInt('your-number-string').toFixed(2)

  • parseFloat('your-number-string').toFixed(2)

  • Number('your-number-string').toFixed(2)

这些中的任何一个都会给你一个数字。

这有帮助吗?

于 2019-10-05T14:00:41.190 回答