Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

String representations of floating-point numbers shall not be compared or inspected. When the value of a float variable must be represented exactly using the double type, an explicit assignment is more appropriate than first converting the floating-point value to a String and then to a double.

Noncompliant Code Example (String Comparison)

This noncompliant code example attempts a string-based comparison of a floating-point number.

...

However s actually contains the string "0.0010". Consequently, the comparison unexpectedly fails.

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.

...

Code Block
bgColor#FFCCCC
int i = 1;
String s = Double.valueOf(i / 10000.0).toString();
s = s.replaceFirst("[.0]*$", "");
if (s.equals("0.0001")) {
  // ...
}

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.

Code Block
bgColor#ccccff
int i = 1;
BigDecimal d = new BigDecimal(Double.valueOf(i / 1000.0).toString())
if (d.compareTo(new BigDecimal("0.001")) == 0) {
  // ...
}

Risk Assessment

Relying on the string representation of floating-point types can result in imprecise values.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

NUM14-J

low

likely

medium

P6

L2

Automated Detection

TODO

Related Vulnerabilities

HV-192

Bibliography

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="1686aac8125857ac-d830a41c-49f440de-8496aa70-e828daf9ca7bd7b3b599689e"><ac:plain-text-body><![CDATA[

[[API 2006

AA. Bibliography#API 06]]

]]></ac:plain-text-body></ac:structured-macro>

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="f0e6bb7ee601e43d-af069b66-48074bfb-a74489f3-7e866a11d5ed6b36cca58a2d"><ac:plain-text-body><![CDATA[

[[JLS 2005

AA. Bibliography#JLS 05]]

]]></ac:plain-text-body></ac:structured-macro>

...