How to calculate % change from X to Y in Python

1 Answer

0 votes
import math

def percent_change(x: float, y: float) -> float:
    return ((y - x) / abs(x)) * 100.0

def describe_change(x: float, y: float) -> str:
    pct = percent_change(x, y)

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

print(describe_change(-80.0, 120.0))
print(describe_change(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%)

"""

 



answered May 29 by avibootz
...