Floating point multiplication in java [duplicate]

社会主义新天地 提交于 2019-12-02 03:47:22

If you want accurate floating point computations, do not use the float or double types, but rather make use of the BigDecimal class.

You cannot. Floating point and double precision numbers in a computer cannot represent all possible values.

This is a side effect of floating point calculations, and is well understood, but not necessarily intuitive. This question has actually been asked literally thousands of times, and you need to study how floating point arithmetic works.

To get around this, if you only need 2-decimal precision, then use a integer instead.

For example, if you're dealing with currency, and you want to buy a 100 items for $4.95, then you represent the cost of that value as the integer "495", an multiply that by 100, which gives you "49500". You always treat the last two digits as cents, so "49500" is $495.00.

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