Float to string method

Started by
5 comments, last by nobodynews 16 years, 4 months ago
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?
Advertisement
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.
Are there any major downsides to the C++/CLI way? I'm wanting to create a DirectX program... will it be sensible to use that way there?
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
The C++ way:
#include <sstream>int main(){float f = 123.456f; // or whateverstd::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]

Tristam MacDonald. Ex-BigTech Software Engineer. Future farmer. [https://trist.am]

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.
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.

C++: A Dialog | C++0x Features: Part1 (lambdas, auto, static_assert) , Part 2 (rvalue references) , Part 3 (decltype) | Write Games | Fix Your Timestep!

This topic is closed to new replies.

Advertisement