Accuracy of double precision multiplication in java?

。_饼干妹妹 提交于 2019-12-01 15:25:28

问题


What is the guaranteed accuracy of multiplication operator for double values in java?

For example, 2.2 * 100 is 220.00000000000003, but 220 is a double number. 220.00000000000003 is the next double after 220.


回答1:


The multiplication is working fine, but 2.2 cannot be represented exactly as a double. The closest doubles are:

  • 2.199999999999999733 (0x4001999999999999)
  • 2.200000000000000177 (0x400199999999999a)

Some software will print the latter value as 2.2, but that doesn't mean it's exact. It just means it's treated as "close enough".




回答2:


If you are working with financials data dont use float or double just use java.math.BigDecimal




回答3:


you can use BigDecimal, but make sure that you use the construct of BigDecimal(String) rather than BigDecimal(double). The difference between them is:



来源:https://stackoverflow.com/questions/6459335/accuracy-of-double-precision-multiplication-in-java

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