Comparing float and double primitives in Java

Take a look at What every computer scientist should know about floating point numbers.

Squeezing infinitely many real numbers into a finite number of bits requires an approximate representation….

— Edit to show what the above quote means —

You shouldn’t ever compare floats or doubles for equality; because, you can’t really guarantee that the number you assign to the float or double is exact.

So

 float x = 3.2f;

doesn’t result in a float with a value of 3.2. It results in a float with a value of 3.2 plus or minus some very small error. Say 3.19999999997f. Now it should be obvious why the comparison won’t work.

To compare floats for equality sanely, you need to check if the value is “close enough” to the same value, like so

float error = 0.000001 * second;
if ((first >= second - error) || (first <= second + error)) {
   // close enough that we'll consider the two equal
   ...
}

Leave a Comment