sprintf(result,"%5lf",test

Solved

Posted on 2004-08-03

I want to convert double to string in C++(linux) I know that there is _ecvt function,

but for only interger that means if I have 10.5 the out put will be 10 only and also I must specifiy the long of number(how many digit)

void main()

{

double test=4.125;

double test;

char *result;

int decimalpt, sign;

cout<<" Enter a number : " ;

cin>>test;

printf ("\n Input was %g \n", test);

// so here I must menstion 3

result = _ecvt(test, 3, &decimalpt, &sign);

printf (" \n Result string is '%s'\n", result);

*/

// strFinalVal contains 4.125

}

what I want I only want to convert from double to string in any way.

Thank You

but for only interger that means if I have 10.5 the out put will be 10 only and also I must specifiy the long of number(how many digit)

void main()

{

double test=4.125;

double test;

char *result;

int decimalpt, sign;

cout<<" Enter a number : " ;

cin>>test;

printf ("\n Input was %g \n", test);

// so here I must menstion 3

result = _ecvt(test, 3, &decimalpt, &sign);

printf (" \n Result string is '%s'\n", result);

*/

// strFinalVal contains 4.125

}

what I want I only want to convert from double to string in any way.

Thank You

9 Comments

spritnf(string,"%lf",doubl

Should do the trick....

Regards

Aakash

/**

* Converts a double into a string with n decimal characters.

* @param d The double to convert.

* @param n The number of digits to the right of the decimal point.

* @return Thr resulting string.

*/

std::string doubleToString( double d, int decimals )

{

std::stringstream ss;

ss.precision( decimals ); // set precision

ss.setf( std::ios::fixed ); // get rid off the scientific notation

ss << d;

return ss.str ();

}

Hope this helps

Tincho

template<typename T> string toString(const T& source)

{

ostringstream oss;

oss << source;

return oss.str();

}

Then, for floats, you can do:

string s = toString(5.4);

But it would also work for ints, bools, etc.

The opposite conversion is simliar.

The viewer will learn how to clear a vector as well as how to detect empty vectors in C++.

Join the community of 500,000 technology professionals and ask your questions.

Connect with top rated Experts

**21** Experts available now in Live!