Dynamic rounding template function

I’d like to express a power entity as W (no decimals) when <1000 W, but kW (one decimal) when >1000 W including the proper units. I could do this with if statements, but was curious if there was a better function for this. Any suggestions? Thanks.

If you plan to do this for a Template Sensor then I don’t recommend it.

A Template Sensor’s unit_of_measurement option only allows you to specify one value (i.e. W or kW). If you want the Template Sensor to use both, depending on whether power is less than or greater than 1000, then you can’t use unit_of_measurement. In other words, you will have to put W or kW directly into the Template Sensor’s state value. That means the Template Sensor’s state value will be non-numeric and can’t be graphed or stored as numerical data in long-term statistics.

If this isn’t for a Template Sensor then you can do it like this:

{% set x = states('sensor.your_power_sensor') | int(0) %}
{{ (x/1000)|round(3) if x > 1000 else x }} {{ iif(x >= 1000, 'kW', 'W') }}

Thanks. It’s for dashboard display purposes only. Your syntax was my plan, but was curious if there was a function that already did something similar.

Jinja2’s built-in filters are listed here.

Home Assistant’s additions to Jinja2 are described here.

The function that most closely approximates what you want is the Immediate If (which I used in the template above).