Convert NSString math equation to value
I would like to know how to evaluate the string representation of an equation as if it were a real equation:
if(@"15+14==23") { //True statement... } else { //False statement.... }
I want to return false, because 15 + 14 is not 23. How can I make this work?
Here is an example of how to do this with NSPredicate
:
NSPredicate *p = [NSPredicate predicateWithFormat:@"1+2==3"]; NSLog(@"%d", [p evaluateWithObject:nil]); p = [NSPredicate predicateWithFormat:@"1+2==4"]; NSLog(@"%d", [p evaluateWithObject:nil]);
The first NSLog
creates 1
because 1+2==3
is true; the second produces 0
.
So, this is a problem that, in my opinion, is much more complicated than the related question allows (although the question is asked by a βsimpleβ parser).
Luckily for you, I think this is a really interesting problem and has already been written for you: DDMathParser
.
It has a good amount of documentation , including such things as how to add it to your project and a high overview of its capabilities . It supports all standard mathematical operators , including logical and comparative operators ( ||
, &&
, ==
!=
, <=
, Etc.).
In your case, you would do something like this:
NSNumber *result = [@"15+14 == 23" numberByEvaluatingString]; if ([result boolValue] == YES) { ....True statement.... } else { .....False statement..... }
As a heads-up, DDMathParser
is licensed under the MIT, which requires you to include copyright information and the full text of the license in everything that uses it.
NSString *equation = @"15+14==29"; NSPredicate *pred = [NSPredicate predicateWithFormat:equation]; NSExpression *LeftExp = [pred leftExpression]; NSExpression *RightExp = [pred rightExpression]; NSNumber *left = [LeftExp expressionValueWithObject:nil context:nil]; NSNumber *right = [RightExp expressionValueWithObject:nil context:nil]; if ([left isEqualToNumber:right]) { NSLog(@"yes left is equal to right"); } else{ NSLog(@"yes left is NOT equal to right"); } NSLog(@"left %@", left); NSLog(@"right %@", right);