-3

I have an issue with the subtraction of two values. when I set discount_amt value to 2.5 then total return me 0.5 but when discount_amt is set to 2.6 it return 0.3999999999999999 instead of 0.4 why?

var total        = parseFloat('3').toFixed(1);
var discount_amt = parseFloat('2.6').toFixed(1);
    total        = total - discount_amt;
    console.log(total);

var total        = parseFloat('3').toFixed(1);
var discount_amt = parseFloat('2.6').toFixed(1);
    total        = total - discount_amt;
    console.log(total);
Bhautik
  • 11,125
  • 3
  • 16
  • 38

1 Answers1

0

This seems to fix it. You forget parsefloat() and tofixed()

total = 3;
discount_amt = 2.6;

console.log(parseFloat(total).toFixed(1) + ' ' + parseFloat(discount_amt).toFixed(1));
total = parseFloat(total).toFixed(1) - parseFloat(discount_amt).toFixed(1);
console.log(parseFloat(total).toFixed(1));

Explanation why floats are handled this way: answer or directly to the link that answer refers to link

Ron Nabuurs
  • 1,528
  • 11
  • 29
  • but i already parseFloat and toFixed to the subtraction time then how could this happened? – Bhautik Apr 04 '18 at 06:47
  • Because you dont parsefloat and tofixed the total. But you should only use toFixed on your answer, because using it before wont help the accuracy of your function – Ron Nabuurs Apr 04 '18 at 06:52
  • ok but i don't know why i still having issue. in you answer output is right but when i apply in my code it still return 0.3999999999999999 – Bhautik Apr 04 '18 at 07:00
  • ok done. thanks sorry i made dumb mistake in my code. – Bhautik Apr 04 '18 at 07:04
  • If you want to know exaclty why javascript isn't accurate you can go to this [answer](https://stackoverflow.com/a/3439981/5686835) or directly to the link that answer refers to [link](http://floating-point-gui.de/) – Ron Nabuurs Apr 04 '18 at 07:39