I have a simple calculator app and I want it to be so that if the answer requires no decimal places, there are none, just whole numbers. If the answer was 2, I don't want it to say 2.000000, it should say 2. If it requires one decimal place, it should show to one decimal place for example 12.8 instead of 12.80. How would I do this? Here is my code.
btw, this is from a tutorial at http://www.youtube.com/watch?v=Ihw0cfNOrr4, not my own work.
viewcontroller.h
#import <UIKit/UIKit.h>
interface calcViewController : UIViewController {
float result;
IBOutlet UILabel *calculatorScreen;
int currentOperation;
float currentNumber;
}
-(IBAction)buttonDigitPressed:(id)sender;
-(IBAction)buttonOperationPressed:(id)sender;
-(IBAction)cancelInput;
-(IBAction)cancelOperation;
@end
in the .m
#import "calcViewController.h"
@implementation calcViewController
-(IBAction)buttonDigitPressed:(id)sender {
currentNumber = currentNumber *10 + (float)[sender tag];
calculatorScreen.text = [NSString stringWithFormat:@"%2f", currentNumber];
}
-(IBAction)buttonOperationPressed:(id)sender {
if (currentOperation ==0) result = currentNumber;
else {
switch (currentOperation) {
case 1:
result = result + currentNumber;
break;
case 2:
result = result - currentNumber;
break;
case 3:
result = result * currentNumber;
break;
case 4:
result = result / currentNumber;
break;
case 5:
currentOperation = 0;
break;
}
}
currentNumber = 0;
calculatorScreen.text = [NSString stringWithFormat:@"%2f", result];
if ([sender tag] ==0) result=0;
currentOperation = [sender tag];
}
-(IBAction)cancelInput {
currentNumber =0;
calculatorScreen.text = @"0";
}
-(IBAction)cancelOperation {
currentNumber = 0;
calculatorScreen.text = @"0";
currentOperation = 0;
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…