PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, August 9, 2022

[FIXED] How to make 2 decimals place in javaScript

 August 09, 2022     decimal, javascript, numbers     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing