Why does casting to float produce correct result in java?

Viewed 366
System.out.println(2.00-1.10)

and

System.out.println((double)(2.00-1.10)) 

both output same result 0.8999999999999999, but

System.out.println((float)(2.00-1.10)) 

outputs 0.9.

Perhaps by default Java performs calculations in double, then why does downcasting corrects result?

And if 1.1 is converted to 1.100000000000001 in double then why does

System.out.println((double)(1.10)) outputs 1.1 only.

EDIT: To get why this happens we need to understand both answers. First the canonical representation is actually different at lower level. Next how the return value of toString is changed/rounded off/matched with the nearest double of argument.

3 Answers
Related