Hello. I have a homework assignment that requires me to create a check writing system. The user will input a dollar amount, say for example $5.36, and the program will generate the equivalent word form of that amount. In this case, it would be "five dollars and 36 cents" (my professor, according to his assignment sheet, would like us to leave the cents as a numerical value). For now, my program will only work for dollar amounts under $10.00. This leads us to my problem. When I enter 2.01, the cents portion becomes 0 cents. However, when I input all other test cases that contain the .01 portion, they all come out to be 1 cent. For some reason that I am trying to figure out, 2.01 comes out to be two dollars and 0 cents. Any suggestion would be great. Thanks!
P.S: I copied and pasted my code, but it doesn't seem like they're indented properly. Is there a way to format it efficiently without going to each line and adding spaces?
Now you're making progress, Simon. However, as a former banker, I can tell you that rounding your numbers when you are dealing with money can get you into legal trouble. What you really need is a way to store your dollars as whole numbers and your cents as whole numbers, so that no rounding is ever required.
Why does rounding get you into trouble? Well, suppose someone deposited two dollars into the bank and then waited to earn some interest on that deposit. And just suppose that the bank were paying a little bit under 1/2 of 1% in interest for, say, a 90-day deposit. Call it .4999%. At the end of the 90 days, that $2.00 deposit will have grown to 2.009998 dollars. If you round that up the nearest cent, you will be adding .0002 cents that the depositer didn't earn. Now do that ten-million times, and you have paid out twenty dollars of excess accumulated interest. Where's that money come from? It gets worse if you end up with totals near the mid-point between your rounding modulus (that is, near a half-penny), which can easily happen with various deposit levels, interest rates, and periods. So, merely rounding to the nearest whole cent isn't a real-world solution to the problem of imprecise floating-point numbers.
Now, you are going to have to round to some modulus at some point; there's no way out of it. But the level of rounding in banks is much finer than the nearest cent. (I can't recall for sure, but I believe we were always told not to round to anything greater than a ten-thousandth of a cent.) But, for your assignment, you don't want to rely on rounding at all. Think about how to treat all of your dollars and all of your cents as integers.
Oh, and here's a handy rule of thumb you should probably consider from now on: never use the "%" operator on anything other than integer data types. It's only a matter of time before you regret it, otherwise.
"Il y a peu de choses qui me soient impossibles..."