Hi I am making an vending machine application. Now the vending Machine takes 5, 10, 20, 50 pence and 1 pound coins. Now I create a String object and use this to read input from the user i.e. read the denomination (Money e.g. 5 or 10 pence) the user enters. Now I parse the string to an double. The user selects an item from the machine which then asks the user to enter coins to complete the purchase. When the user adds 5 pence coins for an item costing 45 pence, a loop is activated to repeat the method in which the coins are to be inserted until the amount entered = or is greater than the price of the snack selected. By the time it gets to 35 pence everything is alright however after adding another 5 pence the number becomes strange

Here is a copy of what happens


Insert Coins : - .05
0.05

Insert Coins : - .05
0.1

Insert Coins : - .05
0.15000000000000002

Insert Coins : - .05
0.2

Insert Coins : - .05
0.25

Insert Coins : - .05
0.3

Insert Coins : - .05
0.35

Insert Coins : - .05
0.39999999999999997

Insert Coins : - .05
0.44999999999999996

Insert Coins : - .05
0.49999999999999994

As such it requires me to enter more money than is necessary.
May you help explain this and possible suggest a solution.

Recommended Answers

All 4 Replies

Please post your code

This is natural behavior for floating point numbers. They are a limited precision representation of a decimal value and you should not expect them to be an exact result. This is why they should not be used for financial calculations which require perfect precision.

You should stick to integers and work with them in terms of cents. So 1 = 1 cent rather than 1 dollar in your example. Calculations could also be unnoticably faster as well.

You should stick to integers and work with them in terms of cents. So 1 = 1 cent rather than 1 dollar in your example. Calculations could also be unnoticably faster as well.

That is a good idea. Floating points normally behave like that, you have explanation on Ezzarals' last post.

Basically used in one format, either in cents or dolors.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.