Template input 230 if sensor value is 0 or unavaliable

Hello all, my first post on the forum!

I’m struggling to code my template to show a default voltage if sensor input is 0 or unavailable, the sensor is giving milliamperes value. Here’s what I have so far in my template.yaml:

  - sensor:
      - name: "Spenning VVB"
        unique_id: 23456765434
        unit_of_measurement: "V"
        device_class: energy
        state_class: measurement
        state: >
          {% set state1 = states('sensor.vvb_strom') %}
          {% if (state1) == 0 %}
            230
          {% else %}
            {{ ((state1|float * 27.2674)/1000 | float ) | round(2) }}
          {% endif %}

This seems to give the else statement even when sensor is 0, however I want it to show 230 if the sensor is 0.
I would also like it to show 230 if the sensor is unavailable, however I haven’t figured a way to script it.

If anyone could point me in the right direction it would be much appreciated.

Frode.

  - sensor:
      - name: "Spenning VVB"
        unique_id: 23456765434
        unit_of_measurement: "V"
        device_class: voltage ### changed
        state_class: measurement
        state: >
          {% set state1 = states('sensor.vvb_strom')|float(0) %}
          {% if state1 == 0 %}
            230
          {% else %}
            {{ ( state1 * 27.2674/1000 ) | round(2) }}
          {% endif %}

Thanks tom_l,

I changed device class, however it still reads back “0” if sensor is 0.

Figured it out for returning ‘230’ when ‘0’:

  - sensor:
      - name: "Spenning VVB"
        unique_id: 23456765434
        unit_of_measurement: "V"
        device_class: voltage ### changed
        state_class: measurement
        state: >
          {% set state1 = states('sensor.vvb_strom')|float(0) %}
          {% if (state1, '0') %} ### 2nd change
            230
          {% else %}
            {{ ( state1 * 27.2674/1000 ) | round(2) }}
          {% endif %}

Now only the ‘unavaliable’ condition remains.

That state isn’t correct. That if statement will always pass, you’ll always get a result of 230. Tom’s template is correct, you should be using that.

Yes, I tested it now, it is now always ‘230’.
My original and Tom’s was giving ‘0’ when sensor is ‘0’, and a wanted floating value based on current from sensor when sensor was >‘0’.

Do you have any suggestion to make it work?

I also changed the template.

Ahh, thanks, yes, your solution is indeed working, my eyes was too fast.

Thanks for all help, will this also handle if the sensor becomes unavailable?

Tested, it works!

Yes unavailable will also be reported as 0. You can change it to be unavailable if you want to by adding this availability template.

availability: "{{ states('sensor.vvb_strom')|is_number }}"