Display Brightness Template Sensor Help

### EXAMPLE 1 ###
 - platform: template
   sensors: 
     dimmer_level_1:
      friendly_name: "Dimmer Level_1"
      value_template: >-
          {% if is_state( "light.esp32_dimming_1", "on" ) %}
            {{ "%2d" | format( states.light.esp32_dimming_1.attributes.brightness | float / 2.55 ) }}%
          {% else %}
             Off
          {% endif %}  

### EXAMPLE 2 ###
 - platform: template
   sensors: 
     dimmer_level_1:
      friendly_name: "Dimmer Level_1"
      value_template: >-
          {% if is_state( "light.esp32_dimming_1", "on" ) %}
            {{ "%2d" | format( states.light.esp32_dimming_1.attributes.brightness | float / 2.55 + 1  ) }}%
          {% else %}
             Off
          {% endif %}  

I am using this sensor to display the brightness percentage in the Frontend.

THE PROBLEM: Use example 1 when the light is at 100% the sensor correctly shows 100%. Anything lower and it’s off by 1. If i set the light to 95% it shows 94%, set it to 80% it shows 79%.

Use example 2, then everything shows up correct, except when the light is at 100%, then it shows 101%.

I have zero to minimal coding skills and put the above code together by copying and pasting things I found in this forum. Is there a way to make it so everything shows correct?

Thanks for any help anyone can give.

Hi I also struggled with this since i wanted to use a mushroom template card and have the percentage show in the secondary row.

After TONS of digging, and reviewing my math…I modified yours and it works on my card as designed, with appropriate rounding:

{% if is_state( “light.office_lamp”, “on” ) %}
{{ “%2d” | format(((states.light.office_lamp.attributes.brightness) / 255*100) | round(0))}}%
{% else %}
Off
{% endif %}

Hope this helps!

If you don’t mind the template reporting 0 when the light is off then you can do it in a single line:

{{ (state_attr('light.office_lamp', 'brightness') | float(0) / 255 * 100) | round(0) }}

If reporting Off is required:

{% set b = state_attr('light.office_lamp', 'brightness') | float(0) %}
{{ (b / 255 * 100) | round(0) if b != 0 else 'Off' }}