Rounding decimal problem with helper template

I know this topic has been covered by many previous posts, but none of the solutions seems to work for me. Doubtless reflects my newbie ignorance.

I’m trying to calculate a daily average for gas usage by dividing the total heating gas used so far this month by the day of the month, but I’m getting 15 decimal places instead of the 2 that I’d like.

If I simplify the template for demonstration purposes by substituting a simple integer in place of total gas used (I’ve used an arbitrary number of 66 here), I get the correct value but not to two decimal places.

{{ (66) / now().strftime("%-d") | round(2, default=0) }} 

This correctly returns 3.6666666666666665 for the 18th day of the month - but not to two decimal places.
Why is that?
Thanks in advance for any help.

If you give the template sensor a unique id you can change the precision from the UI.

Also hat’s not a great default value. You will get divide by zero errors, unless you have an availability template too?

Share the whole sensor config.

{% set ghm = states('sensor.vicare_heating_gas_consumption_current_month') | float %}
{% set gwm = states('sensor.vicare_hot_water_gas_consumption_current_month') | float %}
{{ ((ghm+gwm) * 1.049)/now().strftime("%-d") | round(2, default=0)}}

The “*1.049” is a multiplier to convert volume to cost

You need more parenthesis. You are rounding your strftime before dividing.

But, I agree that you could cause divide by zero issues. Except, probably not on now() for day.

{{ ((66) / now().strftime("%-d")) | round(2, default=0) }}
1 Like

That isn’t the whole sensor config.

i think this “mess it up”, as it makes it a string

In an entity card you can fix it with " format: precision2 "

I’m sorry but I’m unsure what you mean.
I created a helper template with the three lines that I have included. There isn’t anything else.

Ah ok. you did it in the UI. No availability template for you then. Also thinking about it, you don’t need it. If now() goes missing you will have much bigger problems to deal with.

Try this:

{{ (66 / now().day) | round(2, default=0) }}

You can leave out the default if you want.

If it gets set to 0 it will generate an error anyway (divide by zero).