views:

300

answers:

2

Hi, 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?

+13  A: 

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(), ....

Dave DeLong
exactly what i needed thatnks!
Sj
Sweet! I never heard of GCMathParser before.
NSResponder
+11  A: 

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"
newacct
+1 that's really clever! I like how you add the " == 42" to be able to break it up into expressions. Does this support any mathematical functions like sin(), cos(), etc?
Dave DeLong
This is really interesting. I had no idea you could do that. Note that you may need to cast pred as an NSComparisonPredicate (NSExpression *exp = [(NSComparisonPredicate *)pred leftExpression];) to avoid compiler warnings.
Brad Larson
Unfortunately, according to the Predicate Programming Guide, the only supported functions beyond basic arithmetic are sum, count, min, max, average, median, mode, stddev, sqrt, log, ln, exp, floor, ceiling, abs, trunc, random, randomn, and now. So no trigonometry, I guess.
Brad Larson
clever programming !!!! i like it
Biranchi