1

I'm just sitting here programming javascript. And it makes me nuts...

I have a simple calculation.

It's just

var vals = { grossTotal: 3.59, totalPaid: 3.35, alreadyPaid: 0.24 };

var amount = vals.grossTotal - vals.totalPaid - vals.alreadyPaid;

console.log(amount, amount === -Number.EPSILON);

and it always returns me the negative Number.EPSILON How can I get rid of this?

Sebastian Kaczmarek
  • 8,120
  • 4
  • 20
  • 38
  • the values are easy, i was logging them. console.log gives me that: grossTotal: 3.59, given: 0.24 totalPaid: 3.35, alreadyPaid: 0.24 – metalhead666 Feb 05 '20 at 13:02
  • @Ivar that's some kind of hard, i get the values via json from a webinterface... only thing i do is the calculation i already posted and the console.log values – metalhead666 Feb 05 '20 at 13:13
  • I agree with Sebastian here, but I'd like to add [this one](https://stackoverflow.com/questions/3730019/why-not-use-double-or-float-to-represent-currency) to the duplicates as well. Try to avoid numbers with decimal places for currency. Try to store your values as full integers (as cents), do your calculations and eventually divide them by 100. (`((3.59 * 100) - (3.35 * 100) - (0.24 * 100)) / 100` works in this case, but it should be solved at the source.) – Ivar Feb 05 '20 at 13:21
  • It's not JavaScript that is making you nuts, it is floating point numbers. Never do money arithmetic with floating point numbers. Convert to whole integers (pennies) and then do the math. If the values are large enough, you might need to use `BigInt`. – Ben Aston Feb 05 '20 at 13:23
  • thanks a lot, i will calculate with pennies/cents instead of floating numbers – metalhead666 Feb 05 '20 at 13:40

0 Answers0