2

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

Community
  • 1
  • 1
Ben861305
  • 101
  • 8
  • http://stackoverflow.com/questions/6809927/objective-c-how-to-convert-a-string-with-mathematical-expressions-into-a-float?lq=1 –  Sep 19 '12 at 18:05
  • 1
    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

4 Answers4

8

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

msk
  • 8,885
  • 6
  • 41
  • 72
6

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.

Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
2

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

W.K.S
  • 9,787
  • 15
  • 75
  • 122
0

You can replace the characters by this method

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

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.

Fahri Azimov
  • 11,470
  • 2
  • 21
  • 29
cancerian
  • 942
  • 1
  • 10
  • 18