-1

This is so strange, I'm using node for some time now, and I never noticed such a thing. When I try to sum something like 0.7+0.2+0.1 or 0.6+0.3+0.1, the result is 0.9999999999999999. Why isn't the result 1?

I need to validate that the sum of three variables is exactly 1, so I can't round this number, can someone help me understand why node is behaviouring like this? Here is my node version and some more examples/errors on terminal:

enter image description here

Ernani
  • 1,009
  • 3
  • 15
  • 26
  • Asked countless times, another one http://stackoverflow.com/questions/7369803/unexpected-output-when-adding-two-float-numbers – Wiktor Zychla Mar 27 '17 at 20:12

1 Answers1

0

@Aurora0001 thanks for pointing it out. I did search for it but couldn't find the answer. Now I fully understand why Node is doing this, however I'm not sure if I agree to this approach...

Anyway, my workaround was check if the difference between the sum and 1 was below 0.0000000001.

Thanks for your time. Best Regards

Ernani
  • 1,009
  • 3
  • 15
  • 26
  • You can/should use [`Number.EPSILON`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/EPSILON). `const aequal = (a, b) => Math.abs(a - b) < Number.EPSILON` then this will return true `aequal(0.7+0.2+0.1, 1)` – idbehold Mar 27 '17 at 20:44