I'm trying to add the dot functionality to my calculator but I have been struggling getting it to work.
So far what it does is that adds the decimal point but then when I press another number what it does is add 0 regardless the number you pressed..
Example: user input 9 (dot operation/decimal) and then 5 = to 9.0
Which of course is totally incorrect.
Finally, I'm posting specifically the dot function and the number 9 which are the ones that produce that answer.
Header file..
int Method;
float SelectNumber;
float RunningTotal;
bool DecimalActived;
@interface ViewController : UIViewController{
IBOutlet UILabel *Screen;
}
-(IBAction)Number9:(UIButton *)sender;
-(IBAction)Dot:(UIButton *)sender;
@end
Implementation file..(UPDATED)
-(IBAction)Number9:(UIButton *)sender{
[self appendDigit:@"9"];
}
- (IBAction)Dot:(UIButton *)sender {
NSString *currentText = Screen.text;
if ([currentText rangeOfString:@"." options:NSBackwardsSearch].length == 0) {
[self appendDigit:@"."];
}
}
- (void)appendDigit:(NSString *)digit {
// handle two special cases: append to only zero means just replace
// but append decimal point to zero is a regular append
if ([self->Screen.text isEqualToString:@"0"] && ![digit isEqual:@"."]) {
self->Screen.text = digit;
} else {
self->Screen.text = [Screen.text stringByAppendingString:digit];
}
}
Calculations (UPDATED)
- (IBAction)Percent:(UIButton *)sender {
[self MySwitch];
Method = 5;
SelectNumber = 0;
DecimalActived = FALSE;
Screen.text = [NSString stringWithFormat:@"%.2g", RunningTotal];
}
- (IBAction)PositiveOrNegative:(UIButton *)sender {
[self MySwitch];
Method = 6;
SelectNumber = 0;
DecimalActived = FALSE;
Screen.text = [NSString stringWithFormat:@"%g", RunningTotal];
}
-(IBAction)Equals:(UIButton *)sender{
[self MySwitch];
Method = 0;
SelectNumber = 0;
DecimalActived = FALSE;
Screen.text = [NSString stringWithFormat:@"%g", RunningTotal];
}
-(IBAction)AllClear:(UIButton *)sender{
Method = 0;
RunningTotal = 0;
SelectNumber = 0;
Screen.text = [NSString stringWithFormat:@"0"];
}
- (double) MySwitch {
SelectNumber = [[NSNumberFormatter alloc] init];
[SelectNumber setNumberStyle:NSNumberFormatterDecimalStyle];
RunningTotal = [SelectNumber numberFromString:self->Screen.text];
if (RunningTotal == 0) {
RunningTotal = SelectNumber;
} else{
switch (Method) {
case 1:
RunningTotal = RunningTotal * SelectNumber;
break;
case 2:
RunningTotal = RunningTotal / SelectNumber;
break;
case 3:
RunningTotal = RunningTotal - SelectNumber;
break;
case 4:
RunningTotal = RunningTotal + SelectNumber;
break;
case 5:
RunningTotal = RunningTotal / 100;
break;
case 6:
if(RunningTotal > 0){
RunningTotal = - RunningTotal;
} else{
RunningTotal = + RunningTotal;
}
break;
default:
break;
}
}
return RunningTotal;
}
If you guys need more reference to the code please let me know and will supply it or any question to help in this regard let me know too and I will provide the information :)
See Question&Answers more detail:os