Re: sorry .09 instead of .08
joshdalrymple2000@xxxxxxxxx wrote:
double totalCost = 3.91, amountPaid = 4.00;
int totalChange;
totalChange = (int)((amountPaid - totalCost) * 100);
System.out.println(totalChange);
it keeps saying the answer is 8... can any one help?
As has been said, this is due to roundoff error.
If you want to know *why* roundoff error occurs, it helps to know how
primitive floating-point numbers are stored internally. Skipping over
the details, the numbers in your example are stored with the following
bit patterns (shown in hex):
s exp mantissa
3.91 0 400 F47AE147AE148
4.0 0 401 0000000000000
Notice that 3.91 can't be represented exactly. The mantissa is a
repeating fraction, with repeating part 47AE1 that's rounded up at the
end to 48. The internal version of the number is slightly larger than
3.91.
There is no infallible way to deal with this error, since numbers must
always be stored with a finite number of bits. How you deal with it
depends on what you're trying to do.
Financial programs usually adhere to a set of conventions that ensure
that a calculation is *fair*, in the sense that it's always done in the
same way. But this isn't always the same as *accurate*. Credit card
companies and gas stations will always round up, for example.
Storing money amounts in smaller units (e.g. cents or mils instead of
dollars) hides the problem for addition and subtraction, but not for
anything more complicated (compound interest or statistical analysis).
BigDecimal is overkill unless you need more than 15 decimal digits of
precision. It's also extremely limited. There's no pow() method, for
example, so no interest calculations. And the scaling and rounding of
BigDecimals isn't really any easier or less error-prone than the correct
use of primitive floating-point types.
- Ernie http://home.comcast.net/~erniew
.