This is my program so far. I am trying to compute the number of quarters, dimes, nickels, and pennies needed, given an amount (less than $1.00). My problem right now is that when I enter 0.05, I get "1 Nickle and 7.45058e-008 Pennies. Why is it not 0 pennies? If dolamt = 0.05, then 0.05-0.05 should be 0 right?
Also, I am assuming there is a better way of doing this. Anyone want to tell me what I can do to make this easier?
Ok. I just want to get it right though. I don't want it to say "1 Nickle and almost 0 pennies." I want 0. Is there a way to change what I have done to make it like that?
Using == on floating point numbers are generally not a good idea. If I was to do something like this I would store the money as an integer number representing the number of pennies or nickles, whatever is smallest (I don't really know this currency). When you have that you can easily calculate the number of dollars etc. without any rounding errors.
Unless there's good reason to do otherwise (for example, if you need to do currency conversion or other complex financial operations), don't use floating point numbers to store monetary amounts. Use integers and store the number of the smallest unit in the system (e.g. cents). So for example, 100 could represent $1.
The problem with floating point is that it's based on binary encoding, and many common fractional values in currencies, such as 0.01, 0.05, and 0.10, are repeating decimals in binary, meaning floating point representations can't store them exactly in finite memory.
Let's take 1/3 as an example. This is ~0.33333333 in decimal. If we multiply that number by 3 to try and get 1.0 again, we actually get 0.99999999 which is close but not exactly 1. Why? Because we can't write or calculate an infinite number of digits.
0.1 in decimal is 0.000110011001100110011... in binary. It's an infinitly repeating number so if we try and convert that back to decimal, we won't get exactly 0.1 anymore.