String representations of floating-point numbers should not be compared or inspected. If they are used, significant care needs to be taken to ensure expected behavior.
This noncompliant code example incorrectly compares the decimal string literal generated by 1/10000.0
. The string produced is not 0.0001
but rather 1.0E-4
.
int i = 1; String s = Double.valueOf(i / 10000.0).toString(); if (s.equals("0.0001")) { // ... } |
This compliant solution uses the BigDecimal
class to avoid the conversion into scientific notation. It then performs a numeric comparison, which passes as expected.
int i = 1; BigDecimal d = new BigDecimal(Double.valueOf(i / 10000.0).toString()); if (d.compareTo(new BigDecimal("0.0001")) == 0) { // ... } |
Comparing or inspecting the string representation of floating-point values may have unexpected results.
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
NUM11-J | Low | Likely | Medium | P6 | L2 |
Comparing or inspecting the string representation of floating-point values may have unexpected results on Android.
[API 2006] | |
[JLS 2015] | |
[Seacord 2015] |