...
Note that conversions from float
to double
can also lose information about the overall magnitude of the converted value. Specifically, on platforms whose native floating point hardware provides greater precision than double
, the JIT is permitted to use floating point registers to hold values of type float
(or type double
), even though the registers support values with greater mantissa and/or exponent range. Consequently, conversion from float
to double
can cause an effective loss of precision, of magnitude, or of both. However, the lost precision or magnitude would also have been lost if the value were stored to memory, for example to a field of type float
. See guideline FLP04-J. Use the strictfp modifier for floating point calculation consistency for additional information.
...
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); } } |
Note that conversions from long
to either float
or double
can lead to similar loss of precision.
Compliant Solution (ArithmeticException
)
...
In this example, the subFloatFromInt()
method throws java.lang.ArithmeticException
. This approach should be used for conversions from long
to either float
or double
.
Compliant Solution (wider type)
...
Code Block | ||
---|---|---|
| ||
class WideSample { public static int subDoubleFromInt(int op1, double op2) { return op1 - (int)op2; } public static void main(String[] args) { int result = subDoubleFromInt(1234567890, 1234567890); // Works as expected System.out.println(result); } } |
Note that this compliant solution is insufficient 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
.
Risk Assessment
Converting integer values to floating-point types whose mantissa has fewer bits than the original integer value will lose precision.
...