HowDoI: Convert MQTT received value to a 2 decimal place float?

How do I convert an MQTT state topic from a floating point with 6 decimal places (i.e. 5.145245) to a float with 2 decimal places (i.e. 5.15) ?

The MQTT topic is actually a string but HA (cleverly) converts it to a float. I also have the voltage device class in customize.yaml

Values in the front end are correctly displayed but to 6 decimal places.

This is the MQTT sensor:-

hvac_trvs_energenie_8008:
  sensor:
    - platform: mqtt
      state_topic: "/energenie/eTRV/Report/Voltage/8008"
      name: "Lounge TRV Voltage"
      unit_of_measurement: V
      force_update: true

I believe this creates the sensor.lounge_trv_voltage entity? Well I certainly use that in my lovelace cards and the value is displayed.

There may be an easier way, but I would look at a value_template https://www.home-assistant.io/integrations/sensor.mqtt/#value_template

Thanks - but that linked article might as well be in Russian . It’s not far off as it is.

My temperature sensor is mapped to an mqtt topic, as above, how on earth do I start to figure out what a value template needs to be. Is there any [better] documentation to help?

There is a lot of docs on templating. Seek and you shall learn.

1 Like

DO something like this:

  - name: "Temperature WZ 2"
    platform: mqtt
    state_topic: office/sensor3
    unit_of_measurement: °C
    value_template: "{{ value_json.temperature | round(1) - 1 }}"

round(2) will give you the right float number back, and you can do simple calculations too

1 Like

Hi, I found the Template tab on the Developer Tools, I tried this:

{{ states('sensor.lounge_trv_voltage') | float  | round (2) }}

which yields 2.94 in my case. Perfect! float added to force integer to float in the event sensor value is an integer like 1,2,3 …

By the way … round(1) - 1 gave the incorrect value but I get where you are coming from.

All states are text, so you are right, the float is needed to convert from text to number type.

yes, seek and though shall learn mate !

I was too quick. I tried the value_template in the template editor. All seemed well. When I put the code together , viz:-

 - platform: mqtt
      state_topic: "/energenie/eTRV/Report/Voltage/8008"
      name: "Lounge TRV Voltage"
      device_class: voltage
      force_update: true
      value_template: "{{ states('sensor.lounge_trv_voltage') | float  | round (2) }}"

…I always get 0.0

I suspect that it is because the value template is referring to itself? I am at my limits of understanding - for now.

Any ideas anyone?

EDIT: sussed

Just use:

value_template: "{{ value | float  | round (2) }}"

value is predefined and yields value for the current in-scope sensor being defined.

2 Likes