+ 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
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
@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
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.