...
Conversion from int
or long
to float
, or long
to double
may 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. No runtime exception occurs despite this lossDespite this loss of precision, the JLS requires that the conversion and rounding occur silently; that is, without any runtime exception. See JLS, Section 5.1.2, "Widening Primitive Conversion" for more information.
Note that conversions from float
to double
can also lose information about the overall magnitude of the converted value. ( See guideline FLP04-J. Use the strictfp modifier for floating point calculation consistency for additional information.)
Noncompliant Code Example
...
This method may have unexpected results because of the loss of precision. Values of type float
have 23 mantissa bits, a sign bit, and an 8 bit exponent. The exponent allows type float
to represent a larger range than that of type int
. However, the 23-bit mantissa means that float
supports exact representation only of integers whose representation requires more than fits within 23 bits can only be represented approximately by a float
. \; float
supports only approximate representation of integers outside that range.
Code Block | ||
---|---|---|
| ||
class WideSample { public static int subFloatFromInt(int op1, float op2) { return op1 - (int)op2; } public static void main(String[] args) { int result = subFloatFromInt(1234567890, 1234567890); // This prints -46, and not 0 as may be expected System.out.println(result); } } |
...