I'm trying to solve mathematical expressions using NSPredicate and NSExpression.
In case the expression is entered with floating-points at every operand the calculation gets solved correctly.
Expressions, where floating points are missing for some operands, results may be wrong.
To show you what I tried already here is my playgrounds code within i'm testing.
Broken
The calculation of 5 * (5/2)
should result in 12.5, but the expression gives me a result of 10.0, because it calculates 5 * 2
let input1 = "5*(5/2)" // == 10.0, should be 12.5
let predicate1 = NSPredicate(format: "1.0 * \(input1) = 0")
if let comparisation = predicate1 as? NSComparisonPredicate {
let leftExpression = comparisation.leftExpression
if let result = leftExpression.expressionValue(with: nil,
context: nil) as? NSNumber {
print("Result is: \(result.doubleValue)") // == 10.0
}
}
Workaround
To show you that calculating by using NSExpression does actually work, here is my current work around to fix the above result.
let input2 = "5*(5.0/2.0)" // == 12.5
let predicate2 = NSPredicate(format: "1.0 * \(input2) = 0")
if let comparisation = predicate2 as? NSComparisonPredicate {
let leftExpression = comparisation.leftExpression
if let result = leftExpression.expressionValue(with: nil,
context: nil) as? NSNumber {
print("Result is: \(result.doubleValue)") // == 12.5
}
}