I am trying to round the result of a template sensor to 2 decimal places would like some help of how to best place the rounding syntax.
This is what I have so far
sensor:
- platform: alpha_vantage
api_key: !secret alphavantage_key
foreign_exchange:
- from: AUD
to: USD
name: AUD_USD
- from: USD
to: GBP
name: USD_GBP
- from: BTC
to: AUD
name: Bitcoin
## AUS to GBP Conversion - Did this as for some reason alpha vantage doesn't provide AUD to GBP Rates propably due to being USD based site
- platform: template
sensors:
aud_to_gbp:
unit_of_measurement: 'GBP'
value_template: "{{ states('sensor.aud_usd')|float * states('sensor.usd_gbp')|float }}"
friendly_name: 'AUD to GBP'
can I just add something like '%+.2f'|format to the front of the value_template?
Little offtopic, you can try the Developer tools Template page to verify the output
I also just created a template value and also used round(2) a t the end to give it 2 decimals, but if the value_template is alright like that iâm not sure, try with the Developer Tools and then the Template page
The expression doesnât fail, it just doesnât round(2), I have successfully used this function in other templates this is the only one where I am multiplying the result of 2 separate sensors states and need to round the entire. Maybe I need to encompass in brackets
I realise this is an old post, however would be nice to get a solution.
The problem I have, is if the value is, for example: ÂŁ21.10, with the round(2), this shows as ÂŁ21.1. Is there anyway of forcing the 2 decimal places?
Courty40 gave the correct answer. To explain it a bit further:
If you did {{ 10 / 3 |round(2) }} people expect 0.33333 that is rounded to 0.33.
This is not how it works;
first 3 would get rounded to 2 decimals, next 10 is divided by 3.00. This results in 3.3333âŚ
This is logical, since when we do {{ "10" |int / "3" |int |round(2) }}, we would also expect the function to make an int of â10â and an int of â3â before doing the division.
Any function with the piping character always executes on the variable just before the function.
How do you realize the wanted outcome?
you do {{ ( 10 / 3 ) |round(2) }}
The calculation is placed between ( ). This forces it to be calculated and become one variable that is passed to the function behind it.