15 Answers
New Answerto_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
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?
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; }
The_Fox Thanks,But when I print it's length,It comes 3,Why? And what does the line given below work? ss1<<d1;
@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 :)
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?
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.
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.