如何在javaScript中使用2位小数

如何在javaScript中使用2位小数,javascript,numbers,decimal,Javascript,Numbers,Decimal,我需要显示付款总额后的2位小数 我试过这样做: cart.itemsPrice = cart.cartItems.reduce( (acc, item) => acc + (item.price * item.qty).toFixed(2), 0 ); 然后输出如下所示: cart.itemsPrice = cart.cartItems.reduce( (acc, item) => acc + Math.round(item.price * ite

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

我试过这样做:

  cart.itemsPrice = cart.cartItems.reduce(
    (acc, item) => acc + (item.price * item.qty).toFixed(2),
    0
  );
然后输出如下所示:

 cart.itemsPrice = cart.cartItems.reduce(
    (acc, item) => acc + Math.round(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
  );
然后我还是得到了同样的垃圾值


请提供任何建议。

尝试使用此功能,或者如果可能,您可以共享cart.cartItems数组

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

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

因此,最好对reduce函数的结果执行toFixed方法。Math.round也适用于您(Math.round(value*100)/100)(请参阅)

你需要申请固定(2)的整体

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

是的,很管用!谢谢你,伙计