3

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.

tomerpacific
  • 4,704
  • 13
  • 34
  • 52
Alamin
  • 1,878
  • 1
  • 14
  • 34

3 Answers3

3

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);
3

You need apply toFixed(2) on whole.

cart.itemsPrice = cart.cartItems.reduce(
    (acc, item) => acc + (item.price * item.qty),
    0
  ).toFixed(2);
Ayaz
  • 2,111
  • 4
  • 13
  • 16
0

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
  );