I'm trying to do math from a string.
When I turn a string into a math problem with NSExpression, and then get the result with expressionValue, Swift assumes I want an Integer. Consider these two Playground examples:
let currentCalculation = "10 / 6"
let currentExpression = NSExpression(format: currentCalculation)
print(currentExpression) // 10 / 6
if let result = currentExpression.expressionValue(with: nil, context: nil) as? Double {
print(result) // 1
}
let anotherCalculation = "10.0 / 6.0"
let anotherExpression = NSExpression(format: anotherCalculation)
print(anotherExpression) // 10 / 6
if let result = anotherExpression.expressionValue(with: nil, context: nil) as? Double {
print(result) // 1.666666667
}
What should I be doing so that I always get a Double as a result? I don't want to have to parse the string ahead of time.
Pretty interesting that the second example turns "anotherExpression" into Integers, yet still returns a Double as a result.