Float arithmetic is dodgy

Perhaps this isn’t surprising because floats can be a bit funny, but:

(2.0 - 1.0) == 1.0 // true
(2.0 - 1.5) == 0.5 // true
(2.0 - 1.4) == 0.6 // false

In fact most operations like this don’t work as expected (or at least as I’d expect).

This makes unit testing anything involving floats problematic. Is there an approach for this?

Not all rational numbers can be represented precisely in the IEEE 754 floating point format.

2.0, 1.5 and 0.5 can all be represented exactly, that’s why the comparison works.

1.4 and 0.6 can not be represented exactly and in this particular case the resulting rounding error makes the comparison fail.

Here’s a nice explanation: https://floating-point-gui.de/

This makes unit testing anything involving floats problematic. Is there an approach for this?

Use equalWithPrecision.

1 Like