Float and Double for monetary values

2019-07-31 23:28发布

问题:

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!

回答1:

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.



回答2:

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.