How to stop NSExpression from rounding

元气小坏坏 提交于 2019-12-11 04:12:25

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/41455572/how-to-stop-nsexpression-from-rounding

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!