1

I am trying to make a simple a calculator app in Swift + Xcode. I realised that there was a strange issue with the solver: I had used the function shown in this question which works for 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?

1
  • 2
    Integer division I pressume, try sending "3.0/2.0" Commented Nov 19, 2019 at 11:43

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.