Reputation: 11617
public class MyClass {
public static void main(String args[]) {
float x=2.0f;
float y=1.1f;
System.out.println("Float = " + (x - y));
double a=2.0d;
double b=1.1d;
System.out.println("Double = " + (a - b));
}
}
Answer:
Float = 0.9
Double = 0.8999999999999999
I understand if I want better precision, I should have used BigDecimal
, but why float
(which is 32 bit with lesser precision compare to double
) doesn't encounter the rounding issue?
Upvotes: 0
Views: 678
Reputation: 26175
I modified the code to print the exact value of each result immediately after the rounded value:
Float = 0.9
0.89999997615814208984375
Double = 0.8999999999999999
0.899999999999999911182158029987476766109466552734375
The double result is much, much closer to 0.9 than the float result. Those are the values that would have been used in any additional calculations.
The difference in the printout is a consequence of the Float and Double toString methods. Each aims to produce the shortest result that, on conversion back to the corresponding type, would produce the original value. 0.9 would convert to 0.89999997615814208984375 on float parsing. It would convert to 0.90000000000000002220446049250313080847263336181640625 on double parsing. It takes more digits to uniquely identify a double than a float.
Upvotes: 1