I have a float value that needs to be put into a std::string
. How do I convert from float to string?
float val = 2.5; std::string my_val = val; // error here
gcvt() | Convert float value to string in C This function is used to convert a floating point number to string. Syntax : gcvt (float value, int ndigits, char * buf); float value : It is the float or double value. int ndigits : It is number of digits.
To convert float to string, use the toString() method. It represents a value in a string.
toString() method can also be used to convert the float value to a String. The toString() is the static method of the Float class.
As of C++11, the standard C++ library provides the function std::to_string(arg)
with various supported types for arg
.
Unless you're worried about performance, use string streams:
#include <sstream> //.. std::ostringstream ss; ss << myFloat; std::string s(ss.str());
If you're okay with Boost, lexical_cast<> is a convenient alternative:
std::string s = boost::lexical_cast<std::string>(myFloat);
Efficient alternatives are e.g. FastFormat or simply the C-style functions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With