im trying to convert double to string with this code:
if its a number like 3.7345 than its working - but if its 5.0
(only zeros after the point)

double number=5.0;
string ToString;
stringstream out;
out << number;
ToString = out.str();
return ToString;

it returns - 5
and i need it to return - 5.0


i realized that if ill do

double number=5.0;

im getting the number 5 insted of the number 5.0

how do i make the variable hold the zeros after the floating point and show them?

hope both my questions make sense :)
ill apriciate any answer given !

Edited by Drau: n/a

7 Years
Discussion Span
Last Post by Drau

You can't do that because 5.0 is stored as 5.
There is nothing stored about how many insignificant zeroes you entered in your code.


You can simply append 0 since it does nothing:

string toString(const double d, int nZero = 0){
 stringstream stream;
 stream << d;
 return stream.str() + string(nZero,'0');

If you use the double value to print out the value then you can set its precision like so :

double d = 5.0;
cout << d << endl;

or using <iomanip>

double d = 5.0;
cout << setprecision(4) << d << endl;

Edited by firstPerson: n/a


thank you for the answer :)

but 2 last codes doesnt work :
it still prints - 5 (in visual studio)

and as for the first code - the problem is that i dont know if im getting a
5.0 or 3.6 or 0.6 from the user, so i cant always add an extra zero just like that !


Forgot to mention you need to use fixed format:

double d = 5.0;
cout << fixed << setprecision(1) << d << endl;

Edited by firstPerson: n/a

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.