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?
I don’t know if this is the best way, but it’s my prefered way anyhow
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
@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.
OK thanks guys! 2 follow up questions on that method:
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?
Just out of curiosity, does using the (String)voltage cast like I posted actually work? Or would that yield strange behavior over time?
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.
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.