0

I have built a simple text-based calculator with swift. It takes in an expression like 88+9*3 and spits out 115. I am running in to a problem, however. When I do division (like 12/5), the answer comes out rounded (with no decimals). I understand why (when this rounding happens, all of the numbers are integers, so it doesn't convert anything to floats), but how do I stop the rounding when dividing integers?

I can't just add .0 to the end of every number, because then things like 7.6.0 could happen (if the user types in something divided by 7.6), resulting in a crash/no answer.

Here's my code:

func calculateString(calculatorinsert: String) throws -> String {
                var mathExpression = try NSExpression(format: nsexpress)
                var result:Float = try Float((mathExpression.expressionValueWithObject(nil, context: nil) as? NSNumber)!)
                if let calculated: Optional<Float> = result {
                    return String(result)
                } else {
                    return "Error"
                }
            }
4

0 回答 0