CRITICAL
Rule Definition
Due to rounding errors, most floating-point numbers end up being slightly imprecise. As long as this imprecision stays small, it can usually be ignored. However, it also means that numbers expected to be equal (e.g. when calculating the same result through different correct methods) often differ slightly, and a simple equality test fails.
Remediation
Except specific cases where we can expect that the value is the same (see http://randomascii.wordpress.com/2012/06/26/doubles-are-not-floats-so-dont-compare-them), the best is to compare the difference with Epsilon a small float number that you can configure according to the accuracy you want.
Violation Code Sample
float a = 0.15f + 0.15f;
float b = 0.1f + 0.2f;
if(a == b) {...} // VIOLATION
if(a != b) {...} // VIOLATION
Fixed Code Sample
static final float EPSILON = 0.0000001f;
float a = 0.15f + 0.15f;
float b = 0.1f + 0.2f;
if(Math.abs(a - b) < EPSILON) {...} // FIX
if(Math.abs(a - b) > EPSILON) {...} // FIX
Reference
Java Language Specification > 4.2.4. Floating-Point Operations:
http://docs.oracle.com/javase/specs/jls/se7/html/jls-4.html#jls-4.2.4
Doubles are not floats, so don't compare them:
http://randomascii.wordpress.com/2012/06/26/doubles-are-not-floats-so-dont-compare-them/
What's wrong with using == to compare floats in Java?
http://stackoverflow.com/questions/1088216/whats-wrong-with-using-to-compare-floats-in-java
http://floating-point-gui.de/errors/comparison/
Related Technologies
JEE
Technical Criterion
Programming Practices - Unexpected Behavior
About CAST Appmarq
CAST Appmarq is by far the biggest repository of data about real IT systems. It's built on thousands of analyzed applications, made of 35 different technologies, by over 300 business organizations across major verticals. It provides IT Leaders with factual key analytics to let them know if their applications are on track.