I have two values (previous and current) and I want to check change between them (in percent):
(current/previous)*100
But if the previous value is 0 I get Division By Zero, and if value will not change I get 100%.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With