For example:
sum = 0.00;
sum += 46.85 * 0.1;
console.log(sum) // 4.6850000000000005
sum += 179.29 * 0.1;
console.log(sum) // 22.613999999999997
I believe I've had this happen with simple additions and simple multiplications as well.
I understand this is a consequence of the inability to hold floats properly in a computer, which is fine. However, Postgres, as far as I can tell, seems to handle these operations fine with the same numbers. Seems strange that Javascript doesn't seem to, unless I'm missing something.
Anyway, my current fix is to run it like this:
const fixFloatError = (n) => {
decimalDigitLength = n.match(/\.(\d+)/)[1].length;
return parseFloat(parseFloat(n).toFixed(decimalDigitLength - 1));
}
let n = String(46.85 * 0.1);
n = fixFloatError(n);
If you're wondering why I'm converting it to a string beforehand, it's because Javascript will automatically turn a float like 22.6139999999999997 into 22.614 as it enters the function (Which is correctly fixed! Regardless of whether you hardcoded that number into the variable or generated it by multiplication), and things like 4.6850000000000005 into 4.6850000000000005 (which hasn't changed). So to get a consistent function that works for both cases I'm passing in the float as a string to maintain its form.
Surely I'm missing something here and there's a simpler solution?