ZeroDivisionError: float division by zero

The template was working , but suddenly started getting the below error

 "ZeroDivisionError: float division by zero"

what is the reason i am getting the error and how can i fix it to get the percentage of the CPU

- sensor:
      - name: "esxi_vmhost_cpupct"
        unit_of_measurement: "%"
        state: >-
          {{ ((100 * states("sensor.esxi_vmhost_cpuusage")|int) / states("sensor.esxi_vmhost_cputotal")|int) | round(2)}}

i am not an expert with templates

Reason :

returns 0

Check the value under developer tools, states

i was struggling with solution for past 2 hrs and suddenly it works normal :stuck_out_tongue: , not sure why states("sensor.esxi_vmhost_cputotal") returned 0 .

The super class of ZeroDivisionError is ArithmeticError. This exception raised when the second argument of a division or modulo operation is zero. In Mathematics, when a number is divided by a zero, the result is an infinite number. It is impossible to write an Infinite number physically. Python interpreter throws “ZeroDivisionError: division by zero” error if the result is infinite number. While implementing any program logic and there is division operation make sure always handle ArithmeticError or ZeroDivisionError so that program will not terminate.

try:
    z = x / y
except ZeroDivisionError:
    z = 0

Or check before you do the division:

if y == 0:
    z = 0
else:
    z = x / y

The latter can be reduced to:

z = 0 if y == 0 else (x / y)