2

I'm tring to evaluate a string formula to a float but, I cannot find a solution. Here is an example. I need to calculate about 200 formulas in this way.

- NSString *Formula;
- Float  *Result;
- Float *x

- x = 12;
- Formula = @"12.845*x+(-0.505940)";

Result = Evaluation / Calculation (Formula);

Then I'll use Result as a result from formula. --> Result = @"12.845*x+(-0.505940)";

The iOSDev
  • 5,237
  • 7
  • 41
  • 78
fred
  • 45
  • 1
  • 7

3 Answers3

8

You can use NSExpression:

NSString *formula = @"12.845*x+(-0.505940)";
float x = 12.0;

NSExpression *expr = [NSExpression expressionWithFormat:formula];
NSDictionary *object = [NSDictionary dictionaryWithObjectsAndKeys:
                          [NSNumber numberWithFloat:x], @"x", nil];

float result = [[expr expressionValueWithObject:object context:nil] floatValue];
NSLog(@"%f", result);
// Output: 153.634064

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
0

You should do as following:

  1. Substitute x with its value in the string\
  2. Take operands (values) and operators into the stack in the Reverse Polish Notation
  3. Perform calculations
  4. Return result

This is how I would to that.

pro_metedor
  • 1,176
  • 10
  • 17
0

Swifty Answer,

let formula = "12.845*x+(-0.505940)"
let x = 12

let expr = NSExpression(format: formula)
let object = ["x":x]

let result = expr.expressionValue(with: object, context: nil)

print(result)
//Output: 153.63406
Mohammad Zaid Pathan
  • 16,304
  • 7
  • 99
  • 130