Take the 2-minute tour ×

Possible Duplicate:
What is a fast C or Objective-C math parser?

I have a create a function which takes a formula as a NSString. And I have to replace few things in the String and get the value after executing the formula. How can I do this...

Ex: NSString *formulaString = @"((A/B)-1)*100";

Now I can replace A by 20, and B by 10. But how will get calculated value that is ((20/10)-1)*100 as 100

Thanks, Ben

share|improve this question
stackoverflow.com/questions/6809927/… –  user166390 Sep 19 '12 at 18:05
This is where you put to use all that stuff about parsing you were supposed to have learned in the classes you slept through this summer. –  Hot Licks Sep 19 '12 at 18:05
add comment

marked as duplicate by pst, martin clayton, Clyde Lobo, j0k, PaulG Sep 20 '12 at 21:37


4 Answers

up vote 0 down vote accepted

You can replace the characters by this method


NSString *modifiedFormulaString = [formulaString stringByReplacingOccurrencesOfString:@"A" withString:@"10"];

modifiedFormulaString = [modifiedFormulaString stringByReplacingOccurrencesOfString:@"B" withString:@"10"];

But to calculate dat u need to parse it using some parser.

share|improve this answer
add comment

You have to build expression calculator. An open source objective C library I am aware of is GCMathParser

share|improve this answer
Also noteworthy is the excellent DDMathParser library. –  JustSid Sep 19 '12 at 18:00
Thanks a lot MSK... –  Ben861305 Sep 19 '12 at 18:12
Happy to help :) –  msk Sep 19 '12 at 18:12
@MSK whether GCMathParser is for cocoa or cocoa touch? –  vignesh kumar Oct 22 '12 at 9:48
add comment

If your formula is not too complicated, you can use NSExpression:

NSExpression *e = [NSExpression expressionWithFormat:@"((20/10)-1)*100"];
NSNumber *result = [e expressionValueWithObject:nil context:nil];
NSLog(@"%@", result);
// Output: 100

This works even with some functions such as sqrt, exp, ... See the NSExpression documentation for a list of supported function.

share|improve this answer
add comment

You will need to write a mathematical expression parser that takes a NSString * input and yields a numerical output.

share|improve this answer
add comment
