Narrower primitive types can be cast to wider types without any effect on affecting the magnitude of numeric values. However, when the expressions are not strictfp (FLP03-J. Use the strictfp modifier for floating point calculation consistency), conversions from float
to double
may lose information about the overall magnitude of the converted value though the numeric value is preserved exactly (see JLS Section 5.1.2, Widening Primitive Conversion).
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 the this loss. Also, see EXP08-J. Be aware of integer promotions in binary operators.
Noncompliant Code Example
In this noncompliant code example, an a value of type int
is converted to the type float
. Because a floating point
number cannot be precise to 9 digits, the result of subtracting the original from this value is non-zero.
...
The significand part of a floating point
number can hold at most 23 bit values. Anything above this threshold is discarded due to because of precision loss, as demonstrated in this compliant solution.
Code Block | ||
---|---|---|
| ||
class WideSample { public static void main(String[] args) { int big = 1234567890; float approx = big; // The significand can store at most 23 bits if(Integer.highestOneBit(big) <=> Math.pow(2, 23)) { //the significand can store at throw most 23 bits new ArithmeticException("Insufficient precision"); } System.out.println(big - (int)approx); //always prints zero now } else { //handle error throw new ArithmeticException("Insufficient precision"); } } } |
Risk Assessment
Casting numeric types to wider floating-point types may lose information.
...