Floating-point values are compared with == or !=, which rounding makes unreliable

tx0/java:float-equalityrecommendedwarningbug

What it finds

total == 0.3 with a double is false even when total was computed as 0.1 + 0.2: most decimal fractions have no exact binary form, and each operation rounds. Comparing with a tolerance, Math.abs(total - 0.3) < 1e-9, or computing in BigDecimal gives the intended answer.

Reported are == and != with a float or double operand, except comparisons with the literal zero, which are exact for values that were set rather than computed, a comparison of a value with itself, which tests for NaN, and comparisons in assertions.

From the rule's source, float_equality.rs.

Example from the rule's tests
class Prices {  boolean same(double a, double b, float c, int n) {    boolean r = a == b;tx0 reports: a == b compares floating-point values exactly    r = c != 0.5f;tx0 reports: c != 0.5f compares floating-point values exactly    r = a == 0.0;    r = a != a;    r = n == 3;    r = a == n;tx0 reports: a == n compares floating-point values exactly    return r;  }}
Highlighted lines are the ones tx0 reports, with its message under each; the other lines are left alone.

Turn it on, off or suppress it

The rule runs from the recommended tier up. To turn it on in a lower tier, give it a level in tx0.toml:

tx0.toml
[rules]
"tx0/java:float-equality" = "warning"

To keep one finding, suppress it with a reason. tx0 suppress ID --reason "..." writes the comment on the line before the code:

// tx0: ignore[tx0/java:float-equality] reason="..."

tx0 explain tx0/java:float-equality shows the same in the terminal. Found a false positive? Report it.