error during division please help me

I made a calculator in swift ui but the function I made for division works, but it doesn't work correctly, for example to make 25/2= 12.5 mine makes 25/2=12.0 so I round the result I put the function here Below if anyone can help me and write me the correct function, thank you very much in advance everyone :)

func calculate() {
    let expression = NSExpression(format: displayText)
    
    if let result = expression.expressionValue(with: nil, context: nil) as? Decimal {
        let fullOperation = "\(displayText) = \(result)"
        displayText = "\(result)"
        history.append(fullOperation)
    } else {
        displayText = "Error"
    }
}
Answered by szymczyk in 777557022

You are dividing two integers. When the computer divides two integers, it removes the remainder. That is why you get 12.0 when you divide 25 by 2 instead of 12.5.

Convert the integers to Double before doing the division to get the correct value when dividing. See the following Stack Overflow question to learn how to convert an integer to a Double:

https://stackoverflow.com/questions/27467888/convert-int-to-double-in-swift

I don't see any code in your calculate function where you do any calculations so I can't tell you where to put the code to convert to Double. Where do you perform the division?

Accepted Answer

You are dividing two integers. When the computer divides two integers, it removes the remainder. That is why you get 12.0 when you divide 25 by 2 instead of 12.5.

Convert the integers to Double before doing the division to get the correct value when dividing. See the following Stack Overflow question to learn how to convert an integer to a Double:

https://stackoverflow.com/questions/27467888/convert-int-to-double-in-swift

I don't see any code in your calculate function where you do any calculations so I can't tell you where to put the code to convert to Double. Where do you perform the division?

error during division please help me
 
 
Q