What is a simple piece of code to read a stored number, calculate interest on the stored value, say $100, at a rate of %10. Then I store the new value in place of the old one. I was working towards this:
NSNumber *bankTemp = [[NSNumber alloc] initWithInt:[[NSUserDefaults standardUserDefaults] integerForKey:@"bank"]];
bankTemp = bankTemp + (bankTemp * .10);
[[NSUserDefaults standardUserDefaults] setInteger:bankTemp forKey:@"bank"];
bankTemp would be the $100. I am fairly certain that I’m doing something wrong in the middle line. What can I do to correct it?
EDIT: This is NOT homework. I’m working on a trading game app.
EDIT:
I’ve gotten this far now:
NSNumber *bankTemp = [[NSNumber alloc] initWithInt:[[NSUserDefaults standardUserDefaults] integerForKey:@"bank"]];
bankTemp = [bankTemp intValue] * 1.10;
[[NSUserDefaults standardUserDefaults] setInteger:[bankTemp intValue] forKey:@"bank"];
EDIT:
To deal with cents, I’m… omitting them!
The game does not need them so they are not worth the trouble. integers it is.
I am curious to see what solutions people have to dealing with cents though, so please continue to post your thoughts on cents.
You don’t want an NSNumber. NSNumber is a class that wraps around the primitive numeric types so you can use them with, for example, Cocoa collections. If you want to do math, you should just use the primitives. Just do:
And for storing money, you need to consider how you want to treat cents. It’s tempting to use floats so you can literally have 5.25 dollars, but floats are imprecise and cause all sorts of problems when comparing for equality and so on, so it’s usually better to store your currency as an integer in the smallest unit possible and divide to get larger denominations. So if you want to store dollars and cents, represent $100.00 as 10000.