I have experimented what is wrong with float and double types, in Java System.out.print(1-.6) prints .4 and the result is a bit unexpected (0.30000000000000004) in case of System.out.print(1-.7). It would be helpful if anyone is able to direct me towards some resources that explain WHY does it happen. I am assuming its not Java specific its something inherently wrong with these types.
Thanks!
The real types in Java are implementations of IEEE754 single and double precision floating point notation. These are approximations of real numbers rather than exact representations. Some real numbers like 0.8 cannot be represented accurately.
As said Vincent the float
and double
types cannot store values that will not be represented as the sum of 2^-n values (n size depends on the implementation).
Use the BigDecimal class instead.