...
| Code Block | ||
|---|---|---|
| ||
class WideSample {
public static void main(String[] args) {
int big = 1234567890;
float approx = big;
System.out.println(big - (int)approx); // thisThis is expected to be zero but it prints -46
}
}
|
...
| Code Block | ||
|---|---|---|
| ||
class WideSample {
public static void main(String[] args) {
int big = 1234567890;
// The significand can store at most 23 bits
if(Integer.highestOneBit(big) > Math.pow(2, 23)) {
throw new ArithmeticException("Insufficient precision");
}
float approx = big;
System.out.println(big - (int)approx); //always printsPrints zero now when no precision is lost
}
} |
Risk Assessment
Casting numeric types to wider floating-point types may lose information.
...