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 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 Unless you're worried about performance, use string streams:
std::ostringstream ss; ss If you're okay with Boost, lexical_cast is a convenient alternative:
std::string s = boost::lexical_cast<:string>(myFloat); Efficient alternatives are e.g. FastFormat or simply the C-style functions.
As of C++11, the standard C++ library provides the function std::to_string(arg) with various supported types for arg.
You can define a template which will work not only just with doubles, but with other types as well.
template string tostr(const T& t) { ostringstream os; os Then you can use it for other types.
double x = 14.4; int y = 21; string sx = tostr(x); string sy = tostr(y); Use to_string(). (available since c++11)
example :
#include #include using namespace std; int main () { string pi = "pi is " + to_string(3.1415926); cout run it yourself : http://ideone.com/7ejfaU
These are available as well :
string to_string (int val); string to_string (long val); string to_string (long long val); string to_string (unsigned val); string to_string (unsigned long val); string to_string (unsigned long long val); string to_string (float val); string to_string (double val); string to_string (long double val); You can use std::to_string in C++11
float val = 2.5; std::string my_val = std::to_string(val); If you're worried about performance, check out the Boost::lexical_cast library.
This tutorial gives a simple, yet elegant, solution, which i transcribe:
#include #include #include 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