I would like to find a simple method for converting a double to a string,
almost as simple as:
string convertIntToString(int i)
{
stringstream ss;
string str;
ss << i;
ss >> str;
return str;
}
without having to specify how many digits the double number has after the
decimal point.

Please help! Thanks!

RE: string convertDoubleToString(double d)? by armancho_x

armancho_x
Tue May 29 03:37:01 CDT 2007

It' simple;

string convertIntToString(double d)
{
stringstream ss;
string str;
ss << d;
ss >> str;
return str;
}


Here you simply use ouble instead of int; then the overloaded << operator of
stringstream will do the right job for double values.



--
======
Arman


"Ananya" wrote:

> I would like to find a simple method for converting a double to a string,
> almost as simple as:
> string convertIntToString(int i)
> {
> stringstream ss;
> string str;
> ss << i;
> ss >> str;
> return str;
> }
> without having to specify how many digits the double number has after the
> decimal point.
>
> Please help! Thanks!

Re: string convertDoubleToString(double d)? by Ulrich

Ulrich
Tue May 29 06:46:54 CDT 2007

Ananya wrote:
> I would like to find a simple method for converting a double to a string,
> almost as simple as:
> string convertIntToString(int i)
> {
> stringstream ss;
> string str;
> ss << i;
> ss >> str;
> return str;
> }
> without having to specify how many digits the double number has after the
> decimal point.


#include <boost/lexical_cast.hpp>

string const str = boost::lexical_cast<string>(3.14);

BTW:
1. C++ knows function overloading, so you could have named your
function 'convertToString()' instead.
2. C++ knows templates, so you could have make it a template function as
well, but there you are already where boost::lexical_cast<> goes, with the
exception that you don't have the reverse way:

double const d = boost::lexical_cast<double>("3.14");

You can get Boost at http://www.boost.org. It contains several, mostly
independent libraries, so don't be afraid of its size.

Uli