Given two double values d1, d2, what is the most reliable way to test their equality?

Technology CommunityCategory: JavaGiven two double values d1, d2, what is the most reliable way to test their equality?
VietMX Staff asked 3 years ago

The most accurate way to tell whether two double values are equal to one another is to use Double.compare()and test against 0, as in:

System.out.println(Double.compare(d1, d2) == 0);

We can’t use == because of Double.NaN (literally: “Not a Number”). Consider:

final double d1 = Double.NaN;
final double d2 = Double.NaN;

System.out.println(d1 == d2);

will print false.