swift3nsexpression

How to stop NSExpression from rounding


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.


Solution

  • The expression is using integer division since your operands are integers. Try this instead:

    let expression = NSExpression(format: "3.0 / 2.0");
    let answer: Double = expression.expressionValue(with: nil, context: nil) as! Double;
    Swift.print(String(answer));
    

    Consider the following code:

    let answer = Double(3 / 2)
    

    answer in this case would still be 1.0 since 3 / 2 is evaluated to 1 before being inserted in the Double initializer.

    However, this code would give answer the value of 1.5:

    let answer = Double(3.0 / 2.0)
    

    This is because 3.0 / 2.0 will be evaluated based on the division operation for Double instead of the division operation of Integer.