Versions Compared

Key

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

Working with string representations of floating-point values can produce incorrect conclusions about the precision of the values. For example, consider the conversion of a value from type float to type double, a widening primitive conversion. Refer to the guideline "NUM17-J. Beware of precision loss when converting primitive integers to floating-point" for more details about such conversions.

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.

...

Code Block
bgColor#FFCCCC
int i = 1;
String s = Double.valueOf(i / 1000.0).toString();
if (s.equals("0.001")) {
  // ...
}

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

...

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

Thie While the comparison does succeed on this the code .However, the comparison above, it fails on this the similar code below, which uses 1/10000.0 instead of 1/1000.0. The string produced is not 0.00010 but rather 1.0E-4.

...

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

...

Related Vulnerabilities

HV-192

Bibliography

<ac:structured-macro ac:name="unmigrated-wiki-markup

...

" ac:schema-version="1" ac:macro-id="f3363754-98ba-4101-9cc7-fa470ebc54f6"><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="ff4d92f8-710d-44c7-860a-4b60e5183d42"><ac:plain-text-body><![CDATA[

[[JLS 2005

AA. Bibliography#JLS 05]]

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

...

NUM13-J. Do not construct BigDecimal objects from floating-point literals      03. Numeric Types and Operations (NUM)      NUM15-J. Ensure conversions of numeric types to narrower types do not result in lost or misinterpreted data