1

In swift, in Xcode, I am making a calculator app. The app was all working fine but then I realised that the function to solve maths was not working. I had used the function shown in this question. It can solve most problems but when you involve decimal places:e.g. "3/2" you would expect it to return "1.5". It will return 1.0.

Here is the function I am using:

func mathsSolver(item: String) -> String {
    let result = NSExpression(format: item).expressionValue(with: nil, context: nil) as! Double
    return "\(result)"
}

You can call this function with:

print(mathsSolver(item: "3/2")) //this will print 1.0

Any Ideas?

Martin
  • 56
  • 1
  • 11

3 Answers3

2

You have to pass the double value so that you can get result 1.5

print(mathsSolver(item: "3.0/2.0"))

Above you are trying to pass Int value so that it is not giving you the proper result because integer division will always gives you the answer in integer.

Ronak Patel
  • 609
  • 4
  • 16
1

Try:

NSExpression(format: "3.0 / 2.0");

this issue has plenty answears on stackoverflow. Check them out. ^_^ How to stop NSExpression from rounding NSExpression 1/2

1

Its very popular problem. In swift wench you try to divide one Int number by another Int its automatically cleans up everything what must be after doth. For example if you want to divide 5/2 instead 2.5 you will get = 2. In you example swift has deleted everything after doth and instead 1.5 you got just 1.

To resolve this issue try to use Double or Float instead of Int and everything will be fine!