 How to convert double to string? | Sololearn: Learn to code for FREE!

0

# How to convert double to string?

Likewise,We do with int by to_string() method,How to do the same with double?

+3

to_string works with doubles too But if you want greater control over the notation it's written in, the precision etc. It would be better to use stringstreams

+1

Quoi Runtime I don't know tbh.

0

Angelo When i use .length() method after converting double to string by to_string() method,I got 8 which is the size of double datatype. Why?

0

0

Quoi Runtime float a=4.5; cout<<(double)a<<endl;

0

Try this: double t = 4.5; std::string str; str = std::to_string(t); Outputs a string with 6 digits (precision cannot be changed?) or this using sstream: #include <iostream> #include <string> #include <sstream> using namespace std; int main() { ostringstream ss1; double d1 = 4.5; ss1<<d1; string d_str1 = ss1.str(); cout << "Number: " << d1 << '\n' << "to string: " << d_str1; return 0; }

0

Example double d = 22.2; String s = to_string(d);

0

The_Fox Thanks,But when I print it's length,It comes 3,Why? And what does the line given below work? ss1<<d1;

0

@Manav Roy: You mean when you cout << str.length() you get 3? Should be 8... ss1<<d1 adds a string to ss1 and ss1.str() gives you the number as a string. So instead of printing out d_str1 you could also just print out ss1.str(). Here is a documentation on sstreams etc. https://www.tutorialspoint.com/stringstream-in-cplusplus Hope that helps a little :)

0

The_Fox #include <iostream> #include <string> #include <sstream> using namespace std; int main() { ostringstream ss1; double d1 = 4.5; ss1<<d1; string d_str1 = ss1.str(); cout << "Number: " << d1 << '\n' << "to string: " << d_str1.length(); return 0; } d_str1.length() out expected to be 2 as 4.5 are 2 digits,But it came 3,Why?

0

Strange. Should output 8 because with the six-digit precision you get 8 digits: 4.500000. Your output is 3 because you need to count ‚.‘ as a digit: 4.5 thus 3 digits.

0

The_Fox Probably,It might have been rounded,Hence I got 3 digits and not 8.

0

The_Fox How did you put double into the sstream obj as it can only reads string?

0

The_Fox What do the str() function does?

-2

Quoi Runtime If you want to convert int to string, Then, int a=2; string xyz=to_string(a); Now,a is string,If you wanna find it's length,Then you can by .length() method. But if it comes to convert double to string,That is my question.