Float to string

I am trying to publish the temperature value as follows

        float h = dht.getHumidity();
    float t = dht.getTempCelcius();
   client.publish("myPiVal", t );

but get error at line client.publish

How can I convert the float value to string ?



try using String(t)

for example, I have:

Spark.publish("Humidity", "Measured humidity as: " + String(h));

from my own humidity sensor project (you might like to take a peek at: https://github.com/Tinamous/HumidityMonitor as it appears we might be doing something similar!)

Spark.publish(“Humidity”, "Measured humidity as: " + String(h)); Works , but the same logic does not work in below code.
client.publish(“myPiVal”, “Temprature :” + String(h) );
I am actually trying to Publish it to broker using MQQT.

Here relevant code

#include "Adafruit_DHT/Adafruit_DHT.h"

#include "MQTT/MQTT.h"

#define DHTPIN 2     // what pin we're connected to
// Uncomment whatever type you're using!
#define DHTTYPE DHT11		// DHT 11 

void callback(char* topic, byte* payload, unsigned int length);

int lightLevel = 0;


MQTT client("brokerURL", 1883, callback);

// recieve message
void callback(char* topic, byte* payload, unsigned int length) {
    char p[length + 1];
    memcpy(p, payload, length);
    p[length] = NULL;
    String message(p);

    if (message.equals("1"))    
        client.publish("myPiVal","Received 1"); // this publish works 
        client.publish("myPiVal","Did not receive"); // this publish works

void setup() {
    // connect to the server
    client.connect("broker url");
    // publish/subscribe
    if (client.isConnected()) {
        client.publish("myPiVal","Initating ....");

void loop() {
    if (client.isConnected())
        static char tempstr[15];
        float h = dht.getHumidity();
   	    float t = dht.getTempCelcius();
   	//  Spark.publish("Temprature", "Measured Temprature is: " + String(t)); 
    //	Spark.publish("Humidity", "Measured Humidity is: " + String(h));
   	   client.publish("myPiVal", "Temprature :" + String(h) ); //this line creates error 

Find attached the error screen shot. Any help is greatly appreciated.

Sorry. #SteveFail didn’t realise you were using MQTT, that makes it a bit more painful as you need a char[] going through.

Have a look at: http://stackoverflow.com/questions/7383606/converting-an-int-or-string-to-a-char-array-on-arduino

You might also like to look at one of my Arduino MQTT projects which may help with other MQTT things: https://github.com/Tinamous/DeckLights

To get you up and running give this a try (sorry it’s a little hacked as I don’t have the DHT):

  float h = 23.4454;
  float t = 27.557345464;
  //float h = dht.getHumidity();
  //float t = dht.getTempCelcius();
  // Use String to convert the float to a string - theirs probably a better way but this is easy.
  String temperatureString = "Temperature: " + String(t);
  // You might be able to fix this rather than allocate a new char[] every time.
  int length = temperatureString.length();
  char temperature[length];
  // Convert the string to char[]
  temperatureString.toCharArray(temperature, temperatureString.length());
  client.publish("myPiVal", temperature);

Thanks a ton. This did the trick. However I had to change

temperatureString.length() to
temperatureString.length() + 1 in

 // Convert the string to char[]
  temperatureString.toCharArray(temperature, temperatureString.length());

as it was truncating the last character. Thanks Again.

1 Like

Just a quick question…
If I want to convert the part of changing float to required format before publishing , how should the function look…
so that I can use it as

client.publish("myPiVal",  ConvertIntString(2.23));

the below function gives error

char [] ConvertIntString(float intValue){
       //String temperatureString = String(tempInFer);
        String temperatureString = String(intValue);
        int length  = temperatureString.length();
        char temperature[length];
        temperatureString.toCharArray(temperature, temperatureString.length() + 1);
     //    return temperature;

You can also use this (shorter):

float f = 3.1415927;
char buf[10]; // Put whatever length you need here

Some things to note:

  1. This will create and destroy a String object each time. This can be bad for your heap.
  2. At least on Arduino, doing this often enough will crash the program due to heap fragmentation/exhaustion.
  3. The length specified in the toCharArray second argument (10 in this case) is the size of the character array. The particle implementation of this function appears to always create a number that fills the space with the following priorities: There is always a trailing NULL. If the number is negative, a sign will occupy the first character in the array. The integral part of the number is expressed next. Finally, as many decimal digits as will fit are enumerated into the remaining slots in the array.
  4. This has the effect of rendering value such as 42.5 = 42.500000 but in some cases, e.g. 25.8 = 25.799999.

Unfortunately, there does not appear to be a way to indicate that you want a particular number of decimal places in this method.

The dtoa() function appears not to be available in the local IDE, nor is dtostrf(). At least in the version I downloaded on July 24, sprintf with %f does not work (silently renders empty field). The cloud IDE does not appear to be working at the moment (compile attempts result in a 404 error message).

The general prototype for dot appears to be as follows:

dtoa(floating_point_value, mode (you probably want mode 0), decimal_digits, &decpt, &sign, **result)

I wasn’t able to find any real documentation for &decpt, &sign, or the format of **destination. It appears that these are actually return values. (decpt and sign are (uint8_t *) and specify the place for the function to place those values, whatever they are and result is type (char **) such that the function dynamically allocates a char[] to hold the result and then places a pointer to that in the location specified by result. (*result[0] = first character of result).

For your proposed function, try this:

char * ConvertIntString(float Value) {
  String vString = String(Value);
  int length = vString.length() + 1; // +1 allows room for trailing NULL
  char *result = malloc(length * sizeof(char)); // the sizeof here isn't really
                                                // necessary for char, but for
                                                // portability...
  vString.toCharArray(result, length);
  return result;