Search code examples
swiftfunctionequations

Function Keeps Subtracting Instead Of Dividing


Below is the code that I have

let interestone = 0.0485
let interesttwo = 0.0625
let interestthree = 0.0725
let months: Double = Double(leasingTextField.text!)!
if months <= 24 {
    rentePercentLabel.text = String(format: "%.2f%%", 4.85)
    renteLabel.text = String(interestone * (price - payouttwo) / 12 * months)
    totalCostsLabel.text = String(price + (interestone * (price - payouttwo) / 12 * months))
    leasingafgiftLabel.text = String(payouttwo + restsumtwo +
        (interestone * (price - payouttwo) / 12 * months) / months)
}

The line below is the one that is giving me trouble, because instead of performing the two equations and then dividing the months last, what happens is that payouttwo and restsumtwo get added and then the next part is added to that.

leasingafgiftLabel.text = String(payouttwo + restsumtwo + 
    (interestone * (price - payouttwo) / 12 * months / months))

Solution

  • I think you can try this...

    let interestone = 0.0485
    let interesttwo = 0.0625
    let interestthree = 0.0725
    let months: Double = Double(leasingTextField.text!)!
    if months <= 24 {
        rentePercentLabel.text = String(format: "%.2f%%", 4.85)
        let renteLabelValue = interestone * (price - payouttwo) / 12 * months
        renteLabel.text = String(renteLabelValue)
        totalCostsLabel.text = String(price + (interestone * (price - payouttwo) / 12 * months))
        leasingafgiftLabel.text = String((payouttwo + restsumtwo + renteLabelValue) / months)
    }
    

    What I understood from that line was it was not able to calculate values as you were expecting, We can calculate a part of equation before itself and use that in the actual equation.