Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSString to equation

I am using Objective-C and I am trying to set an equation that is stored in an NSString to be evaluated and stored in an NSInteger.

something similar to the following:

equation = [[NSString alloc] initWithString:@"1+5*6"];

and then evaluate that to become 31 and store it into an NSInteger. any ideas how to do this?

like image 228
Sj. Avatar asked Oct 01 '09 04:10

Sj.


3 Answers

You want the wonderful, amazing, and fabulous GCMathParser, available (FOR FREE!) on apptree.net: http://apptree.net/parser.htm It does exactly what you're asking, and even allows you to do variable substitutions (3x+42, evaluate with x = 7). It even has support for mathematical functions like sin(), cos(), tan(), their inverses, dtor(), log(), ....

edit a long time later...

While GCMathParser is pretty awesome, it has the flaw of not being extensible. So if you need a function that it doesn't natively support, then too bad. So I decided to do something about it, and came up with an entirely native math parser and evaluator: http://github.com/davedelong/DDMathParser

like image 187
Dave DeLong Avatar answered Oct 22 '22 11:10

Dave DeLong


You can use the predicate system:

NSString *equation = @"1+5*6";

// dummy predicate that contains our expression
NSPredicate *pred = [NSPredicate predicateWithFormat:
                      [equation stringByAppendingString:@" == 42"]];
NSExpression *exp = [pred leftExpression];
NSNumber *result = [exp expressionValueWithObject:nil context:nil];
NSLog(@"%@", result); // logs "31"
like image 44
newacct Avatar answered Oct 22 '22 12:10

newacct


I have use this on iPhone to evaluate an equation. It's simpler, you don't need to create a NSPredicate, just the NSExpression:

NSString *equation = @"floor((19-10)/2)";
NSNumber *result = [NSExpression expressionWithFormat:equation];
NSLog(@"%@", result); // logs "4"

And here is the docs to the compatible parseable functions: “BNF Definition of Cocoa Predicates”

code shared in Gist here

like image 40
luismesas Avatar answered Oct 22 '22 12:10

luismesas