Versions Compared

Key

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

Narrower primitive types can be cast to wider types without affecting the magnitude of numeric values. See JLS, Section 5.1.2, "Widening Primitive Conversion" for more information. Conversion from int or long to float, or long to double can lead to loss of precision (loss of least significant bits). No runtime exception occurs despite this loss. Also , see guideline EXP05-J. Be aware of integer promotions in binary operators.

Note that conversions from float to double may can also lose information about the overall magnitude of the converted value. (see See guideline FLP04-J. Use the strictfp modifier for floating point calculation consistency for additional information.).

Noncompliant Code Example

...

Automatic detection of casts that may can lose precision is straightforward. Sound determination of whether those casts correctly reflect the intent of the programmer is infeasible in the general case. Heuristic warnings may could be useful.

Related Vulnerabilities

Search for vulnerabilities resulting from the violation of this guideline on the CERT website.

Other Languages

Related Guidelines

This guideline appears in the C Secure Coding Standard as : FLP36-C. Beware of precision loss when converting integral types to floating point.This guideline appears in

the C++ Secure Coding Standard as : FLP36-CPP. Beware of precision loss when converting integral types to floating point.

Bibliography

Wiki Markup
\[[JLS 2005|AA. Bibliography#JLS 05]\] [Section 5.1.2|http://java.sun.com/docs/books/jls/third_edition/html/conversions.html#5.1.2], "Widening Primitive Conversion"

...