3

I am looking to create an iOS calculator, just by using a UITextField. So for example; somebody may type in '6 - 3 x 2' in the UITextField then hit "Done" or "Go" etc. This would then calculate the answer and display it in a UIAlertView.

So firstly I believe that the UITextField text has to be split up into different sections so '6' '-' '3' '*' '2' would be the separated strings from the UITextField text input. How would I go about separating the text like mentioned above?

How can I then use this information to calculate the answer and to display it?

objc-obsessive
  • 825
  • 1
  • 12
  • 18

2 Answers2

5

Use GCMathParser http://apptree.net/parser.htm

It takes an NSString as an input and evaluates it for you.

As Danh said, you can also use DDMathParser https://github.com/davedelong/DDMathParser

An Example(right from the docs)

NSString* mathstring = @"tan(dtor(45))";
double result = [mathstring evaluateMath];    // returns 0.999999999999...

So you simply send message evaluateMath to the NSString you want to parse. That's it)

Nikita Pestrov
  • 5,876
  • 4
  • 31
  • 66
  • 2
    As mentioned here http://stackoverflow.com/questions/4892152/what-is-a-fast-c-or-objective-c-math-parser along with DDMathParser. – danh Apr 21 '12 at 17:26
  • but isn't this for OS X development? I tried downloading the source code and it wanted to compile on my Mac? – objc-obsessive Apr 21 '12 at 17:29
  • 2
    @objc-obsessive - Dave's parser works on both platforms. GCMathParser just needs to have the `#import ` lines changed to `#import `, and then you can just include those source files into your end application. – Brad Larson Apr 21 '12 at 18:27
  • OK, so if I used the `#import ` line - how would I actually integrate it into an existing iOS project? Is it relatively simple? Can you post an answer with a short example of how to do what I'm looking for? – objc-obsessive Apr 21 '12 at 19:07
0

You could also use NSPredicate as such:

NSPredicate * parsed = [NSPredicate predicateWithFormat:@"22/7.0 + (13*42) - 1024 = 0"];
NSExpression * left = [(NSComparisonPredicate *)parsed leftExpression];
NSNumber * result = [left expressionValueWithObject:nil context:nil];
NSLog(@"result: %@", result);

But I'm not sure about functions like tan and such. More info here.

Kamek
  • 3,383
  • 1
  • 16
  • 9