Convert float to std::string in C++


Question

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
1
61
11/16/2016 4:11:31 PM

Accepted Answer

Unless you're worried about performance, use string streams:

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.

53
8/28/2013 9:58:39 AM

As of C++11, the standard C++ library provides the function std::to_string(arg) with various supported types for arg.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon