Goal reached how to show positive number

Hi all,

I’ve gone over my goal of 50km running this week. I’d like to show kilometers_left as a positive number rather than a negative.

{{ states(‘input_number.weekly_run_goal’) | float - states(‘sensor.kms_this_week’) | float }}

Any help would be appreciated :+1:

So, you want that number to be positive whether you are over or under?

Put this into Developer Tools | Template and see if it is what you are after. Of course, I don’t have your entities. So, I just set a couple variables.

{%- set weekly_run_goal = 50 -%}
{%- set kms_this_week = 50.58 -%}
{{ ((weekly_run_goal | float) - (kms_this_week | float)) * (-1 if ((weekly_run_goal | float) - (kms_this_week | float)) < 0 else 1) }}
{{ states('input_number.weekly_run_goal') | float - states('sensor.kms_this_week') | float * (-1 if (('input_number.weekly_run_goal' | float) - ('sensor.kms_this_week' | float)) < 0 else 1) }}

Gives me an error:

ValueError: Template error: float got invalid input ‘input_number.weekly_run_goal’ when rendering template ‘{{ states(‘input_number.weekly_run_goal’) | float - states(‘sensor.kms_this_week’) | float * (-1 if ((‘input_number.weekly_run_goal’ | float) - (‘sensor.kms_this_week’ | float)) < 0 else 1) }}’ but no default was specified

You are missing parenthesis on your original calculation that I added.

{{ states('sensor.kms_this_week') | float - states('input_number.weekly_run_goal') | float }}

Personally, I’d change the state to a non-numeric value describing that you hit the goal. Or make a second template that shows your exceeded goal values.

e.g.

template:
- sensor:
  - name: Running Goal
    unique_id: running_goal
    device_class: distance
    unit_of_measurement: km
    state: >
       {{ [ 0, states('input_number.weekly_run_goal') | float - states('sensor.kms_this_week') | float ] | max }}
    availability: >
      {{ states('sensor.kms_this_week') | is_number }}

  - name: Exceeded Goal
    unique_id: exceeded_goal
    device_class: distance
    unit_of_measurement: km
    state: >
       {{ [ 0, states('sensor.kms_this_week') | float - states('input_number.weekly_run_goal') | float ] | max }}
    availability: >
      {{ states('sensor.kms_this_week') | is_number }}

Cool! This gives me what I want

 {{ [ 0, states('sensor.kms_this_week') | float - states('input_number.weekly_run_goal') | float] | max }}
  

But it has a lot of decimals. How can I get this down from 0.5799999999999983 to 0.58?

Thanks for your help!

Either run another 1.7 femtometers or surround the statement in parentheses and add |round(2) after it.

1 Like

       {{ ([ 0, states('sensor.kms_this_week') | float - states('input_number.weekly_run_goal') | float] | max | round(2)) }}
  

Thanks :+1: