# Thread: Problem multiplying a double

1. Member
Join Date
Oct 2012
Posts
2
Rep Power
0

## 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).

Java 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

2. Moderator
Join Date
Apr 2009
Posts
13,076
Rep Power
23

## 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.

3. ## 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

4. Member
Join Date
Oct 2012
Posts
2
Rep Power
0

## Re: Problem multiplying a double

Thank you for the quick reply

5. Moderator
Join Date
Apr 2009
Posts
13,076
Rep Power
23

## Re: Problem multiplying a double

Or use a BigDecimal.
In the real world you don't use floats or doubles for currency.

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•