【问题标题】:How to make 2 decimals place in javaScript如何在javascript中制作2个小数位
【发布时间】:2021-07-20 11:18:18
【问题描述】:

我需要在付款总额后显示 2 位小数。

我试过这种方式:

  cart.itemsPrice = cart.cartItems.reduce(
    (acc, item) => acc + (item.price * item.qty).toFixed(2),
    0
  );

然后输出显示如下:

$0269.97179.9888.99

我不知道为什么,

那么如果我想这样:

 cart.itemsPrice = cart.cartItems.reduce(
    (acc, item) => acc + Math.round(item.price * item.qty).toFixed(2),
    0
  );

然后我仍然得到相同的垃圾值

请有任何建议。

【问题讨论】:

    标签: javascript numbers decimal


    【解决方案1】:

    尝试使用这个,或者如果可能的话,你可以分享 cart.cartItems 的数组。

    cart.itemsPrice = cart.cartItems.reduce(
        (acc, item) => acc + (item.price.toFixed(2) * item.qty.toFixed(2)).toFixed(2),
        0
      );
    

    【讨论】:

      【解决方案2】:

      好的,toFixed 返回一个字符串 (see docs)。 因此,当您尝试将数字添加到字符串时,它只是将数字转换为字符串并添加两个字符串。您可以使用“+”运算符将值转换为数字acc + +value.toFixed(2);

      所以最好对 reduce 函数的结果执行 toFixed 方法。 Math.round 也应该适合您 (Math.round(value*100)/100)(请参阅docs)。

      console.log((3.033333).toFixed(2) + 4.5) // will print 3.034.5 
      
      cart.itemsPrice = (cart.cartItems.reduce(
        (acc, item) => acc + (item.price * item.qty),
        0
      )).toFixed(2);
      

      【讨论】:

        【解决方案3】:

        您需要整体申请 toFixed(2)。

        cart.itemsPrice = cart.cartItems.reduce(
            (acc, item) => acc + (item.price * item.qty),
            0
          ).toFixed(2);
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2016-03-20
          • 2023-04-09
          • 2016-06-22
          • 2018-01-25
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多