Floating point multiplication in java [duplicate]

…衆ロ難τιáo~ 提交于 2019-12-20 04:50:17

问题


Possible Duplicate:
How to round a number to n decimal places in Java

When multiplying two numbers in java happens this:

double a = 9.495 * 100;

Expected result:

a = 949.5;

But the obtained result is:

a = 949.4999999999999

When I try to round number 9.495 in two decimal places the result is 9.49 instead of 9.50

Any ideas how to solve this problem?


回答1:


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




回答2:


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




回答3:


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.



来源:https://stackoverflow.com/questions/8506019/floating-point-multiplication-in-java

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