String representations of floating-point numbers must not be compared or inspected.
Noncompliant Code Example (String Comparison)
This noncompliant code example compares the string representations of two floating-point values:
The comparison unexpectedly fails because
s contains the string
"0.0010", which is not equal to
Noncompliant Code Example (Regex)
This noncompliant code example attempts to mitigate the extra trailing zero by using a regular expression on the string before comparing it:
Although the comparison succeeds on the preceding code, it fails on the following similar code, which uses
1/10000.0 instead of
1/1000.0. The string produced is not
0.00010 but rather
Compliant Solution (String Comparison)
This compliant solution uses the
BigDecimal class to avoid precision loss. It then performs a numeric comparison, which passes as expected.
Comparing or inspecting the string representation of floating-point values may have unexpected results.
Hibernate Validator bug report HV-192 describes a violation of this rule.
Android Implementation Details
Comparing or inspecting the string representation of floating-point values may have unexpected results on Android.
|||NUM11-J. Do not compare or inspect the string representation of floating-point values LiveLesson|