GitHub
CERT Secure Coding

NUM11-J. Do not compare or inspect the string representation of floating-point values

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.

Noncompliant Code Example (String Comparison)

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 .

Non-compliant code
int i = 1;
String s = Double.valueOf(i / 10000.0).toString();
if (s.equals("0.0001")) {
  // ...
}

Compliant Solution (String Comparison)

This compliant solution uses the BigDecimal class to avoid the conversion into scientific notation. It then performs a numeric comparison, which passes as expected.

Compliant code
int i = 1;
BigDecimal d = new BigDecimal(Double.valueOf(i / 10000.0).toString());
if (d.compareTo(new BigDecimal("0.0001")) == 0) {
  // ...
}

Risk Assessment

Comparing or inspecting the string representation of floating-point values may have unexpected results.

Rule Severity Likelihood Detectable Repairable Priority Level
NUM11-J Low Likely Yes Yes P9 L2

Automated Detection

Tool

Version

Checker

Description

Security Reviewer - Static Reviewer

6.02

StringComparisonFloatFull Implementation

Android Implementation Details

Comparing or inspecting the string representation of floating-point values may have unexpected results on Android.

Bibliography

[ API 2006 ]


[ JLS 2015 ]


[ Seacord 2015 ]