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:
answerin this case would still be1.0since3 / 2is evaluated to1before being inserted in theDoubleinitializer.However, this code would give
answerthe value of1.5:This is because
3.0 / 2.0will be evaluated based on the division operation forDoubleinstead of the division operation ofInteger.