Accuracy with Float Numbers

I am new to C++ and am wriiting a simple program to determine how much change a machine should give and what coins it should return.
I have declared 'costPrice' and 'amountTendered' as floats.
changeGiven is also declared as a float and is:

changeGiven = amountTendered - costPrice;

The change given is then compared with costants e.g:
const float FIVEPOUNDS = 5.00f;

The program does not work. If I enter

costPrice = 2.4
amountTendered = 5

I would expect
changeGiven = 2.6

Instead I am getting
changeGiven = 2.59999999

Please could someone explain how I could get an exact answer such that I get answer of 2.6 and not 2.5999999.

I can do it by working in pence (i.e. converting everything to integeger) but I am curious as to why I am getting this issue.

Thanks
floating points numbers can't store all values exactly. Similar to how you can't write the value of 1/3 exactly. You could use double that has higher accuracy than float but it will still not be the exact.

If you just want the number to look more correct, try to print less decimals.
Here's a good guide: http://floating-point-gui.de/
Topic archived. No new replies allowed.