How to check change between two values (in percent)?
def get_change(current, previous):
if current == previous:
return 100.0
try:
return (abs(current - previous) / previous) * 100.0
except ZeroDivisionError:
return 0
Edit: some have commented that OP was describing a problem with the current code, not asking for this behavior, thus here is an example where, "if the current is equal to previous, there is no change. You should return 0". Also I've made the method return Infinity if the previous value was 0, as there can be no real percentage change when the original value is 0.
def get_change(current, previous):
if current == previous:
return 0
try:
return (abs(current - previous) / previous) * 100.0
except ZeroDivisionError:
return float('inf')
You need to divide the change (current-previous
) by the previous
, not just the current. So, to make a long story short:
change_percent = ((float(current)-previous)/previous)*100
Note that if previous
is 0
you cannot calculate the change in percentage (regardless of the python implementation)