Go Down

Topic: Are there any C++ techniques to convert a 'float' into a 'string' on an Arduino? (Read 332 times) previous topic - next topic



I really don't like the C style of converting floating-point values into strings which is simple yet it complicates my code when trying to write and learn C++, the following is a cut&paste from a answer on stackoverflow.com:
Code: [Select]

// The C way:
char buffer[32];
snprintf(buffer, sizeof(buffer), "%g", myDoubleVar);

// The C++03 way:
std::ostringstream sstream;
sstream << myDoubleVar;
std::string varAsString = sstream.str();

// The C++11 way:
std::string varAsString = std::to_string(myDoubleVar);

// The boost way:
std::string varAsString = boost::lexical_cast<std::string>(myDoubleVar);

I'm afraid that I know too little about those C++ libraries to even find out my self online, those are quite confusing for me to get a grasp of.

Are there any such C++ ways of converting a 'float' or 'double' intro a 'string' for use in software written for and run on an Arduino?


No technical questions via PM. They will be ignored. Post your questions in the forum so that all may learn.


Don't bother to use Strings with Arduino, as they cause memory problems.

The following works quite well to print floats, but if you want a C-string, use dtostrf().
Code: [Select]
float x=1.23;

Go Up