Thanks for reading
Rob Burns wrote:So I currently have working code that calculates the denominations that I need when change is displayed. The problem is that it seems to be missing one cents every time. So if my change prints out $12.35, it will end up being 1 - ten, 2 - ones, 1 - quarter, 1 - nickle, and 4 - pennies rather than 2 nickles. or 1 dime This happens for any dollar amount unless it is even cash and no change, or the change calculates to where there doesn't need to be a penny. Just an FYI, this code is being used in a GUI panel program if it seems strange in anyway. I'll list my code below, and if possible, can anyone tell if there is an error somewhere in it?
Assuming that the total and realTotal variables are floating point variables, what you are seeing are rounding errors. And these rounding errors are caused by the way floating point values are stored.
An easy fix would be to ... add a 1/2 penny to the value before converting it to an integer.
Rob Burns wrote:Just tried it and works like a charm! Thank you kindly sir!
To give a bit more detail... the rounding errors of floating point is actually really small, and should not be noticed in many cases. The problem here is that you are also converting the value to an integer, and to do that, it rounds down to the next whole penny. This means that an error on the negative side, no matter how small, will cause a penny to be lost.
By adding a 1/2 penny, you are changing the algorithm of converting to integer from rounding down to the next whole penny, to rounding to the closest whole penny.