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


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,
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

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

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Maen Abu-TabanjehNetwork Administrator, Network ConsultantCommented:
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.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.