Search code examples
objective-cnsexpression

Why is NSExpression incorrectly evaluating this math expression?


I have the following code:

NSExpression *expression;

@try {
    expression = [NSExpression expressionWithFormat:@"20/100*200"];

    NSNumber *result = [expression expressionValueWithObject:nil context:nil];
}
@catch(NSException *exception){}

Somehow, the result I'm getting back is an NSNumber of 0, instead of 40. What am I doing wrong?


Solution

  • It's doing an integer division instead of a floating point one. Try this:

    expression = [NSExpression expressionWithFormat:@"20.0/100*200"];