Issue
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.
Solution
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);
Answered By - Dmytro Krasnikov Answer Checked By - Cary Denson (PHPFixing Admin)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.