Formatting Numbers

Hi,

Looking for a little help, I’ve been stuck on this problem or a couple of days.

I’m using a Mushroom template card to create a custom display of my Anthem AV receiver’s status. I’m stuck on formatting the number returned for the volume level. Currently the volume on the receiver is configured to report as a percentage. However, the template is displaying it as a decimal number. For example, if the volume is set to 10% the displayed volume is 0.10.

How do I write the following template to display as a whole number with a % sign?

Currently I have:

{{ 'On' if is_state('media_player.anthem_av', 'on') else 'Off' }} - {{state_attr('media_player.anthem_av', 'volume_level') if is_state('media_player.anthem_av', 'on') else ' ' }} - {{state_attr('media_player.anthem_av', 'source') if is_state('media_player.anthem_av', 'on') else 'Off' }}

Which results in:

On - 0.10 - Music

What I’d like to display is:

On - 10% - Music

On it’s own

{{ (state_attr('media_player.anthem_av', 'volume_level') * 100)|int }}%

but probably in your template

{{ ((state_attr('media_player.anthem_av', 'volume_level')*100)|int)|string + '%' }}

You can also use Python style formatting.

{{ '{:.0%}'.format(state_attr('media_player.anthem_av', 'volume_level')) }}
1 Like

Awesome, this worked. I wasn’t aware I could use python formatting. I appreciate your help.

1 Like

Yeah, it’s not documented, but I came across it somewhere on the forum. Very useful.

Hi @parautenbach,
Just came across the python style formating and it works great.
Thanks for posting.

1 Like

That’s awesome!
And it worked well in the Developer Tools experimental area.
However, when I defined a new sensor in configuration.yaml with this style of formatting I just get “undefined” as result. :flushed:
Anyone any idea why this might be?

Here’s the snippet from the - sensor: section:

  - name: "StudioPod Volume"
    unique_id: "StudioPodVolume"
    unit_of_measurement: "%"
    icon: mdi:volume-equal
    state: >-
        {{ '{:.0%}'.format(state_attr('media_player.studiopod', 'volume_level')) }}

Without the '{:.0%}'.format(...) I get the value that’s between 0 and 1. :man_shrugging:

When you specify that unit of measurement, don’t have the extra percentage sign in the format function and ensure your value is in the range 0…100, not 0…1.

But, you can actually just do this:

{{ state_attr('media_player.studiopod', 'volume_level') | multiply(100) }}

State attributes preserve their type, so no need for a float filter.

If this seems confusing: the previous answer assumed there was no unit of measurement: just a template sensor with a text value (not a numeric one), preformatted. If you want that, remove the unit of measurement. Otherwise, use the solution given here.

1 Like