-1

I am trying to get an output of 4.01 but I am getting 4.013000000000005 instead. The first time I ran the code, I thought the problem was that I didn't have parseFloat but it still doesn't run. This is the code:

var num = 194.092;
var amount = 198.103;
console.log(amount - parseFloat(num.toFixed(2)));
VLAZ
  • 26,331
  • 9
  • 49
  • 67
  • try `var finalResult = amount - parseFloat(num); console.log(finalResult.toFixed(2))` – CAMD_3441 Jan 29 '21 at 21:39
  • 1
    Does this answer your question? [How to deal with floating point number precision in JavaScript?](https://stackoverflow.com/questions/1458633/how-to-deal-with-floating-point-number-precision-in-javascript) – evolutionxbox Jan 29 '21 at 21:39
  • [Is floating point math broken?](https://stackoverflow.com/q/588004) – VLAZ Jan 29 '21 at 21:40
  • This will work - console.log((amount - num).toFixed(2)); – ch_g Jan 29 '21 at 21:43

1 Answers1

0

You need to parseFloat the result.

var num =194.092;
var amount = 198.103;
console.log(parseFloat(amount - num).toFixed(2));
Jose Marin
  • 802
  • 1
  • 4
  • 15