Template sensor shows as 'Unavailable' even though the value exists

I’m trying to format a counter helper for use in my dashboard. So I’ve created a template sensor which looks like this;

- sensor:
    - name: meterCounterDisplay
      icon: mdi:meter-gas
      device_class: gas
      state_class: measurement
      state: >
        {{ '{0:,.3f}'.format( states('counter.gaszahler_h') | float * 0.001) }}

When I paste the state
{{ '{0:,.3f}'.format( states('counter.gaszahler_h') | float * 0.001) }}
into the developer tools template editor then I get the value I expect, such as 14,026.519

But when using this entity in my dashboard, it shows as ‘Unavailable’.

So what have I done wrong?

Remove the comma.

{{ '{0:.3f}'.format( states('counter.gaszahler_h') | float(0) * 0.001) }}

Thanks, but it hasn’t made any difference!

I added your Template Sensor to my system.

  • When I leave the comma in place, an error is logged and the system refuses to create the sensor entity.

  • When I remove the comma, a warning is logged because the sensor’s device_class is gas but it’s missing unit_of_measurement with either ft³, , or CCF.

  • When I remove the comma and add unit_of_measurement: 'm³' the sensor is created and displays a numeric value.

Add the unit_of_measurement option as shown below (change if you’re using a different unit system):

- sensor:
    - name: meterCounterDisplay
      unique_id: meter_counter_display
      icon: mdi:meter-gas
      device_class: gas
      unit_of_measurement: 'm³'
      state_class: measurement
      state: >
        {{ (states('counter.gaszahler_h') | float(0) * 0.001) | round(3) }}

EDIT

Ensure you add unique_id as well.

Got it working!! Great, thanks a lot for your help.

I did have to change state_class to ‘total_increasing’, otherwise I was getting an error in the logs.

Thanks.

You’re welcome!

Please consider marking my post above with the Solution tag. It will automatically place a check-mark next to the topic’s title which signals to other users that this topic has been resolved. This helps users find answers to similar questions.

For more information about the Solution tag, refer to guideline 21 in the FAQ.


Regarding measurement or total_increasing, the choice the depends on your intended application.

Do note that the formatting won’t work. If the value is something like 12,345.100 the state will be 12345.1