How to convert MQTT Value to numeric value

Hey guys,
I have a device, that is sharing its battery state via MQTT. The problem is, that its value is “100 %”, “99 %” and so on … I implemented it in home assistant like this:

- platform: mqtt
  name: "Robonect Batterie"
  state_topic: "robonect/mower/battery/charge"

This is working, but in home assistant the history of the sensor is showed like state changes, instead of a numeric value (since in MQTT the value is a string instead of a numeric value).

How can I change this?

Adding

  unit_of_measurement: '%'

Will convert it to a numeric sensor. But better yet, adding this instead:

  device_class: battery

Will give it a numeric value and a battery icon that changes depending on state of charge.

1 Like

Somehow this isn’t working. I think the problem is, that the value in MQTT is “100 %” (with % included)… its not just a number without the “%”…
I tried what you said, but this didn’t change anything, I still get this:
Bildschirmfoto 2020-06-04 um 19.23.41

You can remove that easily enough:


- platform: mqtt
  name: "Robonect Batterie"
  state_topic: "robonect/mower/battery/charge"
  value_template: "{{ value | replace('%', '') }}"
  device_class: battery
1 Like

Thank you for your help. This deleted the “%” but still its shown like that:

Its working after I also added

unit_of_measurement: '%'

to the sensor. Thank you for your help sir! :slight_smile:

Btw.: Is it possible to replace more values with your method? This is an example:
I have a device (also MQTT) that gives different states with numbers from 0 to 3. Is it possible to replace all values to something else: 0 to Auto, 1 to Manuell, 2 to Home, 3 to EOD.

An alternative way to remove the terminating % is using python’s ability to slice a string.

This will slice off the last character (regardless of what it may be):

  value_template: "{{ value[:-1] }}"

If there is a space between the numeric portion and the % symbol then you’ll want to slice off the last two characters.

  value_template: "{{ value[:-2] }}"
1 Like