如何在 javaScript 中保留 2 位小数
How to make 2 decimals place in javaScript
我需要在付款总额后显示2位小数。
我试过这种方法:
cart.itemsPrice = cart.cartItems.reduce(
(acc, item) => acc + (item.price * item.qty).toFixed(2),
0
);
然后输出显示如下:
69.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
);
好的,固定returns一个字符串(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);
整体需要申请到Fixed(2)
cart.itemsPrice = cart.cartItems.reduce(
(acc, item) => acc + (item.price * item.qty),
0
).toFixed(2);
我需要在付款总额后显示2位小数。
我试过这种方法:
cart.itemsPrice = cart.cartItems.reduce(
(acc, item) => acc + (item.price * item.qty).toFixed(2),
0
);
然后输出显示如下:
69.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
);
好的,固定returns一个字符串(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);
整体需要申请到Fixed(2)
cart.itemsPrice = cart.cartItems.reduce(
(acc, item) => acc + (item.price * item.qty),
0
).toFixed(2);