You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 81 Current »

String representations of floating-point numbers should generally 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.

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.

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

Remediation Cost

Priority

Level

NUM11-J

Low

Likely

Medium

P6

L2


Android Implementation Details

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

Bibliography



  • No labels