Float and Double for monetary values

拈花ヽ惹草 提交于 2019-12-24 10:42:11

问题


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.



来源:https://stackoverflow.com/questions/4354710/float-and-double-for-monetary-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!