Convert float to text

Using this code:

    on_value:
      then:
        - mqtt.publish_json:
            topic: domoticz/in
            payload: |-
              root["idx"] = 259;
              root["nvalue"] = 0;
              root["svalue"] = id(roomtemp).state;

My mqtt subscriber gets this payload:

{“idx”:259,“nvalue”:0,“svalue”:20.125}

The problem is I need the temperature (20.125) to be a string such that in the payload it has quotes around it like this:

{“idx”:259,“nvalue”:0,“svalue”:“20.125”}

Can someone please help me solve this? Thank you.

try if it accepts:
id(roomtemp).state.c_str()

That does not work. I forget the exact error because I had tried that a while ago. Thank you though.

Did you try if the payload will take an Arduino String class? Below code will initialize the String to the numeric value in the parameter. If the payload needs a c string the .c_str() can be added after the last ). For idf framework might need to add correct #include or use std::string.

‘’’
root[“svalue”] = String( id(roomtemp).state );
‘’’

That worked! How simple. Here’s the working code:

sensor:
  - platform: dallas_temp
    id: roomtemp
    name: "Room Temperature"
    update_interval: 10s
    on_value:
      then:
        - mqtt.publish_json:
            topic: domoticz/in
            payload: |-
              root["idx"] = 259;
              root["nvalue"] = 0;
              root["svalue"] = String(id(roomtemp).state);

A payload of {“idx”:259,“nvalue”:0,“svalue”:“20.125”} is delivered. Thank you so much!

1 Like