Im working on a calculator app which works with doubles and then when you press equals the operation is done with doubles then switched to NSNumberFormatter. My problem is when the user wants to add (or -,/,*) a number to the answer on the screen. If the number on the screen has no commas, everything works fine, if the number on the screen does have commas I get a random number instead of the correct answer. Any suggestions?
here is my code for the equals button. I have the same code for every operation. Please excuse my terrible naming
also test.firstnumbers
is a a string that stores the numbers before the user enters in the second set of numbers for the math problem
double number = [test.firstNumbers doubleValue];
double otherNumber = [self.label.text doubleValue];
double answer = number + otherNumber;
NSNumberFormatter *finalAnswer = [[NSNumberFormatter alloc]init];
[finalAnswer setNumberStyle:NSNumberFormatterDecimalStyle];
self.label.text = [finalAnswer stringFromNumber:[NSNumber numberWithDouble:answer]];
double otherNumber = [self.labelTwo.text doubleValue];
You never want to use the view that displays the results as the storage for your data. That's a violation of the MVC paradigm, and just generally a poor plan. You should have the number in the display stored in your data model (even if that "model" is as simple as an instance variable in your view controller). Among other benefits, this avoids the need to convert the number to text and then back to a number, and therefore entirely avoids the problem you're having with commas.
Taking a look at the direct cause of the problem, you're using NSString's -doubleValue
method to convert from string to number, but using the number formatter to convert from number to string. As you've seen, the two aren't exactly complementary. Use the number formatter for both conversions and you'll have better luck. But, again, you really shouldn't be using the view to hold the operand.