We help IT Professionals succeed at work.

Is there a way to convert a float value to a std::string?

tmitch68 asked

I have some code that works - but it's a little clunky:

char szItemCost[100];
sprintf_s(szItemCost,"%.2f", itemCost);

std::string strItemCost = szItemCost;

Is there away to directly convert a float value to a std::string?

Thanks in Advance,
Watch Question

Top Expert 2012
Just use a std::stringstream, e.g.
#include <sstream>
#include <string>
using namespace std;

float f = 123.45;

stringstream ss;

ss << f;

std::string strItemCost = ss.str();

Open in new window

Maen Abu-TabanjehNetwork Administrator, Network Consultant
Top Expert 2011
suppose we have :

float val = 2.5;
std::string my_val = val; // error here

Open in new window

std::ostringstream ss;
ss << myFloat;
std::string s(ss.str());

Open in new window

If you're okay with Boost, lexical_cast<> is a convenient alternative:

std::string s = boost::lexical_cast<std::string>(myFloat);

Open in new window

good luck
Note that your format string "%.2f" does not do what you seem to be hoping for.
the .2 refers to precision not number of decimal places.

The following still does not do what you intend but matches what you have written as your example.

#include <sstream>
#include <iomanip>

std::ostringstream ss;
ss << std::setprecision(2) << myFloat;
std::string s(ss.str());

If you need to get a specific number of decimal places in your output first manipulate the value so that is actually truncated at the decimal accuracy you require.