How to calculate % change from X to Y in Swift

1 Answer

0 votes
import Foundation

func percentChange(_ x: Double, _ y: Double) -> Double {
    return ((y - x) / abs(x)) * 100.0
}

func describeChange(_ x: Double, _ y: Double) -> String {
    let pct = percentChange(x, y)

    if pct > 0 {
        return String(format: "From %.1f to %.1f is a %.2f%% increase (+%.2f%%)",
                      x, y, pct, pct)
    } else if pct < 0 {
        return String(format: "From %.1f to %.1f is a %.2f%% decrease (%.2f%%)",
                      x, y, abs(pct), pct)
    } else {
        return String(format: "From %.1f to %.1f is no change", x, y)
    }
}

print(describeChange(-80.0, 120.0))
print(describeChange(120.0, 30.0))
print(describeChange(90.0, 90.0))



/*
run:

From -80.0 to 120.0 is a 250.00% increase (+250.00%)
From 120.0 to 30.0 is a 75.00% decrease (-75.00%)
From 90.0 to 90.0 is no change

*/

 



answered 47 minutes ago by avibootz
...