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;
This tutorial gives a simple, yet elegant, solution, which i transcribe:
#include <sstream>
#include <string>
#include <stdexcept>
class BadConversion : public std::runtime_error {
public:
BadConversion(std::string const& s)
: std::runtime_error(s)
{ }
};
inline std::string stringify(double x)
{
std::ostringstream o;
if (!(o << x))
throw BadConversion("stringify(double)");
return o.str();
}
...
std::string my_val = stringify(val);
You can use std::to_string in C++11
float val = 2.5;
std::string my_val = std::to_string(val);
You can define a template which will work not only just with doubles, but with other types as well.
template <typename T> string tostr(const T& t) {
ostringstream os;
os<<t;
return os.str();
}
Then you can use it for other types.
double x = 14.4;
int y = 21;
string sx = tostr(x);
string sy = tostr(y);
If you're worried about performance, check out the Boost::lexical_cast library.
Use std::to_chars once your standard library provides it:
std::array<char, 32> buf;
auto result = std::to_chars(buf.data(), buf.data() + buf.size(), val);
if (result.ec == std::errc()) {
auto str = std::string(buf.data(), result.ptr - buf.data());
// use the string
} else {
// handle the error
}
The advantages of this method are:
Unfortunately std::to_string
is of limited utility with floating point because it uses the fixed representation, rounding small values to zero and producing long strings for large values, e.g.
auto s1 = std::to_string(1e+40);
// s1 == 10000000000000000303786028427003666890752.000000
auto s2 = std::to_string(1e-40);
// s2 == 0.000000
C++20 might get a more convenient std::format
API with the same benefits as std::to_chars
if the P0645 standards proposal gets approved.
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.