Hi all,
I am working through book exercises for C#. And one of the questions is to convert a monetary amount, represented by a double.
I have encountered a small error when I try to extract the penny value from this Double value:
for example:
I input 47.32. I use the formula/code:
int penniesToConvert = (int)((moneyIn - Math.Truncate(moneyIn)) * 100);
This takes the double value, subtracts the Integer part, multiplies by 100 to make .32 into the Integer 32, and casts it to be placed in a new Integer type. This is then used for calculations later.
Until now, I assumed this was fine, and it gave me an Integer value of 32. I changed the penny value of the original double to test it; 13, 47, 63 etc.
It's only when I input .33, that the Integer I get back is 32. I extracted the part of moneyIn - Math.Trunc... (without multiply by 100) and when I look through the debugger, I get a value of .3299999999... Which, when multiplied and casted, becomes 32. The same happens with the value 66. Why is this, is there anyway to account for these, or is my method of extracting the penny value incorrect here.
On a sidenote, this is only in Chapter 2 of the book, so I can't imagine that the solution should be too complicated.
Any help on this would be much appreciated.
Stitchs.