Calculating interest in objective c?
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] i开发者_Go百科ntegerForKey:@"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:
NSInteger bankTemp = [[NSUserDefaults standardUserDefaults] integerForKey:@"bank"];
bankTemp = bankTemp + bankTemp * 0.10;
[[NSUserDefaults standardUserDefaults] setInteger:bankTemp forKey:@"bank"];
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.
The most significant problem is that you can't multiply a NSNumber that way. NSNumber is an instance, not a scalar type. Stick with multiplying real numbers, as floats or integers.
(I'd suggest a float.)
Edit: Scratch that, you can't do multiplication like that with an NSInteger.
As an abstract, to get 10% added to a value, you can do Value * 1.10 If you just want to know what 10% of a value is, do value * 0.10
If you're looking at doing monthly calculations, or interest over time, you'll need to use one of those formulas.
精彩评论