开发者

Float and Double for monetary values

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 W开发者_如何学CHY 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜