Search code examples
objective-cios7nsexpression

Doing math with NSExpression using parenthsis


I haven the NSString @"200 * (1 + (5 / 100))",

when I put it into a NSExpression *expression = [NSExpression expressionWithFormat:myString];

and NSLog expression I it returns the string. When I however call [[expression expressionValueWithObject:nil context:nil] doubleValue] I get a result of 200.

Can NSExpressionnot handle two sets of parenthesis? Is the another solution with using NSExpression - I don't want to use any of the MathLibraries, because I just have very simple math equations.

Thanks


Solution

  • Of course it can handle two sets of brackets, your problem is simply in the types of your values.

    When you write 200 * (1 + (5 / 100)) all these values are treated as integers, and integer arithmetic is used. This means that 5 / 100 evaluates to 0 and that's why you get 200 as the result. If it were 5.0 / 100 (notice the decimal point), then you'd be getting the right result, as that division would be treated as a float division.