Template returning number in developer tools, string in sensor

Hi, I have a snippet of code which returns a number in developer tools, but when used as a sensor it is treated as text → history is filled with text instead of a graph.

This is the code:

{% set tracking = "starlink" %}

{% set satellites = states("sensor.satellites_overhead_satellites") %}
{% set ns = namespace(count=0) %}
{% for i in range(satellites|int) %}
  {%- if tracking in state_attr("sensor.satellites_overhead_satellites", "sat_" ~ (i + 1) ~ "_name") | lower %}
  {% set ns.count = ns.count + 1 %}
  {%- endif -%}
{% endfor %}
{{ ns.count }}

What am I doing wrong?

You need to give it a unit of measurement to get the graph generated. Nothing to do with strings vs numbers.

Set the unit of measurement to “sat” or something (can be anything) and it’ll start drawing a graph, although it’ll need all the past records to “flush out” before it does it properly.

Just FYI, states are always strings. They are treated as numbers by the frontend if they have a unit of measurement as Troon pointed out.

However there is another “gotcha” involved in this. The template editor “interprets” results. If it looks like a number it will be typed as a number. State templates do not do this. I created an issue for this to be removed because it confuses the heck out of people, but I was told “no”.

Indeed, adding a unit of measurements solves it - great, thanks. Just as a side note: no need for flushing, apparently including a unit of measurement is applied retroactively.

I thought I knew about states being always strings, but was thrown off track by the template editor cheerily displaying a result type “number”. Thanks for the explanation, and count me under “people being confused the heck out of”.

2 Likes