...
Here is an example of what could happen :
| Code Block | ||
|---|---|---|
| ||
class Test{
public static void main(String[] args){
int big = 1999999999;
double big_float = big;
float one = 1.0f;
System.out.println(big*one);
System.out.println(big_float);
}
}
|
The output is
2.0E9
{{1.999999999E9}}
while the expected output is :
2.0E9
2.0E9.
big is first converted to a float, and loses some precision, which explains the 2.0E9. However, big_float doesn't lose any precision since it's a wider type than float, this is why the two output are different.
...
In that particular case, it would be sufficient to use a double instead of a float :
| Code Block | ||
|---|---|---|
| ||
class Test{
public static void main(String[] args){
int big = 1999999999;
double big_float = big;
double one = 1.0d;
System.out.println(big*one);
System.out.println(big_float);
}
}
|
...