pythonmathpercentage

How to check change between two values (in percent)?


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%.


Solution

  • 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')