Xcode How to evaluate String formula with expression X inside

I am trying to evaluate the string formula for a float, but I cannot find a solution. Here is an example. So I need to calculate about 200 formulas.

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

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

Result = Evaluation / Calculation (Formula);

Then I will use Result as a result of the formula. → Result = @ "12.845 * x + (- 0.505940)";

+2
source share
3 answers

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

It even works with some functions, such as sqrt, exp... See. Documentation NSExpressionfor a list of supported features.

+8
source

You should do the following:

  • Replace x with your value in the string \
  • ()

.

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
0
source

Source: https://habr.com/ru/post/1528857/


All Articles