0

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

Joseph
  • 9,171
  • 8
  • 41
  • 67

1 Answers1

2

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.

micantox
  • 5,446
  • 2
  • 23
  • 27
  • Can I force it to always calculate as double? The string is user inputted and they could also enter something like "99/2" which is not supposed to be evaluated as integer division. – Joseph Jun 27 '14 at 08:58
  • I'm afraid there's not such a way, you'll have to implement some parsing/replacing logic to the string – micantox Jun 27 '14 at 09:07
  • ok - thanks... Then I will have to include DDMathParser into my project. Wanted to prevent using 3rd party libraries, but oh well. ;) – Joseph Jun 27 '14 at 09:17