I've been making a calculator in Swift 3, but have run into some problems.
I have been using NSExpression to calculate the users equation, but the answer is always rounded.
To check that the answer was rounded, I calculated 3 / 2.
let expression = NSExpression(format: "3 / 2");
let answer: Double = expression.expressionValue(with: nil, context: nil) as! Double;
Swift.print(String(answer));
The above code outputs 1.0, instead of 1.5.
Does anyone know how to stop NSExpression from rounding? Thanks.
The expression is using integer division since your operands are integers. Try this instead:
Consider the following code:
answer
in this case would still be1.0
since3 / 2
is evaluated to1
before being inserted in theDouble
initializer.However, this code would give
answer
the value of1.5
:This is because
3.0 / 2.0
will be evaluated based on the division operation forDouble
instead of the division operation ofInteger
.