# Problem multiplying a double

• 10-09-2012, 06:02 PM
TheKingpin
Problem multiplying a double
Hello

I'm pretty new to Java and was practising by putting together a calculator which would work out how many of each note and coin demonination make up the change given with a certain monetary total. eg £1.22

It seems to work for EVERY starting figure other than 19.99. I have narrowed down the cause of the problem. It seems to be coming from the multiplication used to convert the figure from pounds to pence (or dollors to cents etc depending on where you're from).

Code:

```double change; change = 19.99 * 100; System.out.println(change);```
The above code for some reason produces a result of 1998.9999999999998 rather than the desired result of 1999.

This appears to happen for 16.99, 17.99 and 18.99. Every other number seems to be worked out correctly ie 15.99 produces the desired figure of 1599.

Does anyone have any idea what is going on here and how this can be resolved.

Kind regards
• 10-09-2012, 06:05 PM
Tolls
Re: Problem multiplying a double
Floating points are not precise, anymore than 0.33333 is the same as 1/3.
Or, you could just read Goldberg.
• 10-09-2012, 06:11 PM
JosAH
Re: Problem multiplying a double
Welcome to the wonderful world of floating point numbers; the number 0.1 can't be represented by the IEEE754 floating point number format system, that's why you get those funny results. Not everything is lost though: add 1/2 a penny to the result and then take the integer part, e.g. (int)(1998.99999999998+0.5)

kind regards,

Jos
• 10-09-2012, 06:12 PM
TheKingpin
Re: Problem multiplying a double
Thank you for the quick reply
• 10-10-2012, 09:51 AM
Tolls
Re: Problem multiplying a double
Or use a BigDecimal.
In the real world you don't use floats or doubles for currency.