Peter V
Peter V

Reputation: 2488

Ways of making a plus/minus button on a calculator work

I'm trying to make a plus/minus button on a calculator work, the idea is basically that what the displayed number should be multiplied by -1, unless if it is equal to 0.

I thought I would do it this way;
if greater than 0, prepend a "-" sign,
if less than 0, delete the first character in the string (which is then "-"),
if equal to 0, leave it that way.

That's how I started with

- (IBAction)plusminusPressed:(id)sender
{   

NSString *minusString = [NSString stringWithFormat:@"-"];
NSString *mainLabelString = mainLabel.text;


if (mainLabelString > 0)
    mainLabel.text = [minusString stringByAppendingFormat:mainLabelString]; 

}

And although it does work with numbers greater than 0, it does just add a minus before 0 and numbers less than 0.
How can I get it to work with the other two possibilities, I've tried adding

 else if ([mainLabelString isEqualToString:@"0"])
    mainLabel.text = [mainLabelString];  

but then it expects an identifier. What should I do about the other two possibilities, did I even do the first one ok?
Would You do it some other way instead?

Upvotes: 0

Views: 3878

Answers (3)

lakshmen
lakshmen

Reputation: 29084

I attempted this as well on my calculator. would like to share my answer with you.

- (IBAction)plusminusPressed{
    if ([TextInput.text isEqualToString:@"0"]) {
        return;
    }else{
        NSString * negative = @"-";
        if(!changingSign){
            changingSign = YES;
            TextInput.text= [negative stringByAppendingString:TextInput.text];
        }else{
            changingSign = NO;
            TextInput.text = [TextInput.text substringFromIndex:1];
        }
    }

}

Hope this helps..

Upvotes: 2

Ajeet
Ajeet

Reputation: 892

The reason you getting the error because you are trying to compare an NSString with numerical 0:

if (mainLabelString > 0)

That's not how it works in Obj-C. You have to compare the value of "mainLabelString" with 0 like

[mainLabelString intValue] > 0

or

[mainLabelString doubleValue] > 0

or

[mainLabelString floatValue] > 0

Checkout the iOS tutorial on iTunes Univ by Standford Univ - Developing Apps for iOS. It has a chapter on building a simple calculator.

Upvotes: 2

Midhun MP
Midhun MP

Reputation: 107191

Why are you making it so complex.

You need to use a float or int variable for doing this.

declare an integer like:

int result;

And store the value in the result variable.

You need to add the result to label like:

mainLabel.text = [NSString stringByAppendingFormat:@"%d",result];

No need of that condition too.

Upvotes: 1

Related Questions