Floating point multiplication in java [duplicate]

2019-03-01 04:21发布

问题:

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.