Best way to convert float to String?


#1

Hi all,

I’ve been poking around this forum as well as stack overflow for c/c++ and am a bit confused on the best way to convert a float (or other) type to a String for publishing variables to the particle cloud.

Is using a (String) type cast valid? Or is there a better method? For example - can I simply cast as below, and then publish the voltString variable to the particle cloud?

void loop(){
    float voltage = analogRead(inputPin);
    String voltString = (String)voltage;
}

Thanks!


#2

I don’t know if this is the best way, but it’s my prefered way anyhow :wink:

char str[16];
float f = 123.456789;
snprintf(str, sizeof(str), "%.2f", f);

This will give you a C string with two decimal places.
And that’s especially convenient when you want to have multiple variables and possibly some text with it
Like

char str[64];
float f1 = 123.456789;
float f2 = -23.456789;
snprintf(str, sizeof(str), "{\"SomeField\":\"%.2f\", \"SomeOther\":\"%.3f\"}", f1, f2);

#3

@mattw, another way is to use ‘C’ strings instead of Arduino Strings and take advantage of the sprintf() function:

char voltString[20];  // size to largest number of chars to display plus a terminating NULL
 
void loop(){
    float voltage = analogRead(inputPin);
    sprintf(voltString, "voltage = %2.4", voltage);
}

The sprintf() function gives you a lot of flexibility in formatting the string that gets stored in the voltString char array. You can refer to the printf() reference for all the formats you can apply.

OMG!!! @ScruffR beat me to it!! :confused:


#4

OK thanks guys! 2 follow up questions on that method:

  1. I saw using sprintf as an option in another post, but also saw that sprintf(%f) had been removed from the photon’s system firmware. Looks like this was an older version (0.4.0) though… do you know if that has been since fixed?

  2. Just out of curiosity, does using the (String)voltage cast like I posted actually work? Or would that yield strange behavior over time?


#5
  1. that limitation had been lifted a long time ago. It was an original tribute to the limited memory of the Spark Core but new ways to “link” these functions and the bigger mem on its successors allowed to bring it back.

  2. Don’t know, but I thought it was just a typo and you actually meant String(voltage) which constructs a new String object to “wrap” the value. But if there were an overload for (String)float then it could work.

But then again, String objects are using dynamic memory allocation and extensive use of them might cause heap fragmentation, so I’d always use C strings where I exactly know what’s happening.


#6

Great explanation. That’s super helpful. Thanks so much!


#7

Thanks @peekay123 @ScruffR for the help!


#8

ScruffR’s example is an awesome example on how to use snprintf!!! :))