Rounding with steps of 5

Hi, I have a very simple calculation which I want the output to be in steps of 5, preferably always rounding up

1.237 → 5
4.67 -->5
8.5 -->10
etc

I also want to cap the output to be between 40 and 95 (this bit works)

- platform: template
    sensors:
      target_soc:
        friendly_name: Target SOC for Night Charge
        unit_of_measurement: "%"
        value_template: >-
          {{ [0, [100 - 3.37*( states('sensor.solcast_forecast_today') |round(0, "ceil", default)), 95] | min] | max }}

How do i do this?

Cheers

{% set state = states('sensor.solcast_forecast_today') | float(0) %}
{%- set x = (((state + 5) // 5) | round(-2, 'half')) * 5 %}
{{ ([40, x, 95] | sort)[1] }}

EDIT: I may have gone overboard with the rounding… :man_facepalming:
@Hellis81’s template is cleaner, just apply the (@tom_l patented :slight_smile: ) range limiter to it…

{% set state = states('sensor.solcast_forecast_today') | float(0) %}
{% set y = (((state/5) | int) +1) * 5 %}
{{ ([40, y, 95] | sort)[1] }} 

Not sure how to incorporate it to your template but rounding up to nearest 5 is:

{{ (((X/5) | int) +1) * 5}}

Replace the X with your state.

1 Like

many thanks both :slight_smile:

You had the right idea (using round filter with the ceil option) but you missed two steps.

The rule of thumb is:

  1. Divide the value by the step-size (5).
  2. Round the result up.
  3. Multiply by the step-size (5).

Example:

{% set x = (states('sensor.solcast_forecast_today') | float(0) / 5) | round(0, 'ceil') * 5 %}
{{ ([40, x, 95] | sort)[1] }}

Hellis81’s version divides by 5, uses int to effectively round the value down, then adds 1 to effectively round the value up, then multiplies by 5. Same principle, different execution.

That is because I couldn’t find a ceil.
I tried | ceil but then I gave up and created my own ceil :slight_smile: