Sign in to follow this  

Float to string method

This topic is 3666 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi there, I was using a piece of sample code (C++, Visio2005), and I when I declared a float, it came with methods such as 'tostring'. It was a very helpful method, but it doesn't come by default. What do I need to include / do to make this happen?

Share this post


Link to post
Share on other sites
You were probably looking at a C++/CLI program. C++/CLI is a separate language from standard C++ that shares a lot of traits with standard C++. In it, you can call ToString() on a float or an int and quite a few other things, for that matter. In order to use it, the simplest way would be to create your project as a C++/CLI project, which involves selecting one of the project types in the CLR folder when you create your project.

Share this post


Link to post
Share on other sites
you could always do it the C way,


float number = 123.213f;
char floatToString[21] = "";
snprintf(floatToString,20,"%f",number);
floatToString[21] = 0;


then use the floatToString variable to do whatever it is that you want to accomplish... I doubt that is what you want to do because you're obviously looking for the quick n' dirty way :P


ZeuC

Share this post


Link to post
Share on other sites
The C++ way:

#include <sstream>

int main()
{

float f = 123.456f; // or whatever

std::ostringstream oStr;

oStr << f;

std::string value = oStr.str();

}




Edit: Thanks raz0r, I seem to type too quickly these days ;)

[Edited by - swiftcoder on December 2, 2007 2:59:18 PM]

Share this post


Link to post
Share on other sites
Quote:
Original post by swiftcoder
#include <sstream>

int main()
{

float f = 123.456f; // or whatever

std::ostringstream oStr;

oStr << f;

std::string value = oStr.str();

}

Fixed.

Share this post


Link to post
Share on other sites
or the boost way:
float f = 1234.5678;
std::string s = boost::lexical_cast<std::string>(f);


This requires boost which you can get pretty easily through Boost Consulting or from Boost directly. Most of boost resides entirely in header files including, I believe, lexical_cast. But there are a few nifty Boost libraries that do need to be compiled which you can circumvent with Boost Consulting.

Share this post


Link to post
Share on other sites

This topic is 3666 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this