Reputation: 2165
I need to show 2 decimals place after the total amount of payment.
I have tried this way:
cart.itemsPrice = cart.cartItems.reduce(
(acc, item) => acc + (item.price * item.qty).toFixed(2),
0
);
then output show me like this:
$0269.97179.9888.99
I don't konw why,
then If I try to like this:
cart.itemsPrice = cart.cartItems.reduce(
(acc, item) => acc + Math.round(item.price * item.qty).toFixed(2),
0
);
then still I got the same garbage value
Any Suggestion please.
Upvotes: 3
Views: 795
Reputation: 1004
Ok, toFixed returns a string (see docs).
So when you are trying to add a number to a string, it just converts the number to a string and adds two strings. You can convert back value to number by using "+" operator acc + +value.toFixed(2);
So it would be better to perform toFixed method on the result of your reduce function. Math.round should also work for you (Math.round(value*100)/100) (see 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);
Upvotes: 3
Reputation: 2121
You need apply toFixed(2) on whole.
cart.itemsPrice = cart.cartItems.reduce(
(acc, item) => acc + (item.price * item.qty),
0
).toFixed(2);
Upvotes: 3
Reputation: 38
Try using this or if possible can you share the array of cart.cartItems.
cart.itemsPrice = cart.cartItems.reduce(
(acc, item) => acc + (item.price.toFixed(2) * item.qty.toFixed(2)).toFixed(2),
0
);
Upvotes: 0