Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: normativized, got two (normative) exceptions

...

Conversion from int or long to float, or long to double can lead to loss of precision (loss of least significant bits). In this case, the resulting floating-point value is a rounded version of the integer value, using IEEE 754 round-to-nearest mode. Despite this loss of precision, the Java Language Specification requires that the conversion and rounding occur silently, that is, without any runtime exception. See the JLS, §5.1.2, "Widening Primitive Conversion" for more information. Therefore, any conversion from an int or long to a floating-point type, or from long to double must be checked against the range that the flowting-point type can precisely represent.

Note that conversions from float to double can also lose information about the overall magnitude of the converted value. See rule "NUM06-J. Use the strictfp modifier for floating-point calculation consistency across platforms" for additional information.

...

Note that this compliant solution cannot be used when the primitive integers are of type long because Java lacks a primitive floating-point type whose mantissa can represent the full range of a long.

Exceptions

NUM14-EX0: Conversions from integral types smaller than int need no precision range check when being converted to floating-point. Conversions from int to double also need no precision range check.

NUM14-EX1: Conversion from integral types to floating-point types need no range check if the subsequent value does not need to be precise. In such cases, it must be documented that the loss of least significant bits of precision is acceptable.

Risk Assessment

Converting integer values to floating-point types whose mantissa has fewer bits than the original integer value can result in a rounding error.

...

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="3cd31f0cfeee8274-b47f9e53-4ba844cb-9ce18940-59c2765ec37b205617cff0e9"><ac:plain-text-body><![CDATA[

[[JLS 2005

AA. Bibliography#JLS 05]]

[§5.1.2, "Widening Primitive Conversion"

http://java.sun.com/docs/books/jls/third_edition/html/conversions.html#5.1.2]

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

...