Search code examples
javascriptjqueryfloating-pointsubtraction

How subtraction of two float values in JavaScript?


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


Solution

  • 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