package main
import (
"fmt"
"math"
)
func percentChange(x, y float64) float64 {
return ((y - x) / math.Abs(x)) * 100.0
}
func describeChange(x, y float64) string {
pct := percentChange(x, y)
if pct > 0 {
return fmt.Sprintf(
"From %.1f to %.1f is a %.2f%% increase (+%.2f%%)",
x, y, pct, pct,
)
} else if pct < 0 {
return fmt.Sprintf(
"From %.1f to %.1f is a %.2f%% decrease (%.2f%%)",
x, y, math.Abs(pct), pct,
)
}
return fmt.Sprintf("From %.1f to %.1f is no change", x, y)
}
func main() {
fmt.Println(describeChange(-80.0, 120.0))
fmt.Println(describeChange(120.0, 30.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%)
*/