comparing float/double values using == operator

Viewed 31976

The code review tool I use complains with the below when I start comparing two float values using equality operator. What is the correct way and how to do it? Is there a helper function (commons-*) out there which I can reuse?

Description

Cannot compare floating-point values using the equals (==) operator

Explanation

Comparing floating-point values by using either the equality (==) or inequality (!=) operators is not always accurate because of rounding errors.

Recommendation

Compare the two float values to see if they are close in value.

float a;
float b;

if(a==b)
{
..
}
9 Answers
Related