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?
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
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"
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With