Versions Compared

Key

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

...

Conversion from int or long to float or from long to double can lead to loss of precision (loss of least significant bits). In these cases, 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 (JLS) requires that the conversion and rounding occur silently, that is, without any runtime exception (see the JLS, §5.1.2, "Widening Primitive Conversion" [JLS 20052015], for more information). Conversions from integral types smaller than int to a floating-point type and conversions from int to double can never result in a loss of precision. Consequently, programs must ensure that conversions from an int or long to a floating-point type or from long to double do not result in a loss of required precision.

...

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

NUM13-J-EX0: Conversion from integral types to floating-point types without a range check is permitted when suitable numerical analysis demonstrates that the loss of the least significant bits of precision is acceptable.

...

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

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

NUM13-J

Low

Unlikely

Medium

P2

L3

Automated Detection

Automatic detection of casts that 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 could be useful.

ToolVersionCheckerDescription
CodeSonar
Include Page
CodeSonar_V
CodeSonar_V

JAVA.CAST.FTRUNC

Cast: Integer to Floating Point (Java)

Parasoft Jtest
Include Page
Parasoft_V
Parasoft_V
CERT.NUM13.AICAvoid implicit casts from integer data types to floating point data types
PVS-Studio

Include Page
PVS-Studio_V
PVS-Studio_V

V6011

Related Guidelines

Bibliography

...


...

Image Modified Image Modified Image Modified