-1

i am working with crypto currency wallets and every coin have its own decimal values like btc has upto 8 decimal eth has upto 18 decimal

i am facing the issue with decimal fixing

    var amount = "0.224424";
    var fee = "0.006069";
    var t_amount = amount - fee;
    t_amount = Number((t_amount).toFixed(18));

and the anwer i am getting in t_amount variable is

0.21835500000000002 

but i dont want this value like it has many zeros and at the end a 2

i want this like below

    0.21835500000000002 => 0.218355
    0.018565000005      => 0.018565
    0.0013320001        => 0.001332

anyone have the idea how to fix this issue..?

Ahsan Malik
  • 111
  • 1
  • 10
  • The operation you're looking for is *rounding* (see the [linked question's answers](https://stackoverflow.com/questions/11832914/how-to-round-to-at-most-2-decimal-places-if-necessary)), or if it's just for display [`toFixed` as shown here](https://stackoverflow.com/questions/3163070/javascript-displaying-a-float-to-2-decimal-places).. But you can't reliably use JavaScript's `number` type for financial calculations ([more here](https://stackoverflow.com/questions/588004/is-floating-point-math-broken)), especially ETH which has more precision that `number` does. – T.J. Crowder Aug 13 '21 at 11:15
  • Have you tried `.toFixed(6)` instead of `.toFixed(18)`? – Jamiec Aug 13 '21 at 11:15
  • so why are you doing `toFixed(18)` when you only need `toFixed(6)`? – Dmitry Kostyuk Aug 13 '21 at 11:15
  • because 18 is decimal value of ethereum coin is there a way to count number of zero in this value 0.21835500000000002 – Ahsan Malik Aug 13 '21 at 11:20

1 Answers1

0

Just change your toFixed(18) into toFixed(6):

var amount = "0.224424";
var fee = "0.006069";
var t_amount = amount - fee;
t_amount = Number((t_amount).toFixed(6));
console.log(t_amount)
Giovanni Esposito
  • 10,696
  • 1
  • 14
  • 30
  • 1
    Rounding and formatting are **very well covered** in previous questions and answers, no need for new ones (or at least, not here -- you could post on the dupetargets). – T.J. Crowder Aug 13 '21 at 11:17