Also, consider that *all calculations* should be performed in *cents* and not inThe double value that I'm trying to convert to GCSMoney (which is
dollars. You should never have to "round" anything like '1.115'.
implemented as cents) was produced by multiplying a dollar amount by
an interest rate to get interest.
double amount = 126.60;
double interestRate = .075;
double interest = amount * interestRate;
int interestAsCents = interest * 100.0 + 0.5;
The debugger says interest = 9.495.
But when I convert it to cents, we see that interest really wasn't
9.495 since the cents rounds to 949 instead of 950.
Below is code where I do my calculations as cents. I can convert
amount to cents by multiplying by 100 since I'm dealing with a dollar
amount. But interest rate is not a dollar amount. I can't convert it
to cents. In this particular case, I can convert it to an integer by
multiplying by 1000 since it has three decimal places.
double amount = 126.60;
double interestRate = .075;
int amountAsCents = amount * 100; // = 12660
int interestRateAsInt = interestRate * 1000; // = 75
int interestTemp = amountAsCents * interestRateAsInt; // = 949500
interestTemp += 500; // round it. = 950000
int interestAsCents = interestTemp / 1000; // undo interestRate
* 10000. = 950
So this works. But what if I have an interest rate that has more
decimal places? For example, 0.1234? Then I would have to convert
it to an int by multiplying by 10000 and later divide by 10000.
In general, if I had a money class that stored money amounts as cents
and I needed a multiplication operator that could multiply a money
type by a double, how would I implement that? Would I just
arbitrarily choose the amount of double precision like this?:
Clint
int precision = 3;
double amount = 126.60;
double interestRate = .075;
int amountAsCents = amount * 100; // = 12660
int interestRateAsInt = interestRate * pow( 10.0, precision ); //
= 75
int interestTemp = amountAsCents * interestRateAsInt; // = 949500
interestTemp += 5 * pow(10.0, precision - 1 ); // round it. = 950000
int interestAsCents = interestTemp / pow(10.0, precision); //
undo interestRate * 10000. = 950
Or instead of hardcoding the precision in the code above, could I
detect how many decimal places there are and use that as my precision?