double val = 0.1;
std::stringstream ss;
ss << val;
std::string strVal= ss.str();
In the Visual Studio debugger, val
has the value 0.10000000000000001 (because 0.1 can't be represented).
When val
is converted using stringstream, strVal
is equal to "0.1"
. However, when using boost::lexical_cast, the resulting strVal
is "0.10000000000000001"
.
Another example is the following:
double val = 12.12305000012;
Under visual studio val
appears as 12.123050000119999, and using stringstream and default precision (6) it becomes 12.1231. I don't really understand why it is not 12.12305(...).
Is there a default precision, or does stringstream have a particular algorithm to convert a double value which can't be exactly represented?
Thanks.
The StringStream class in C++ is derived from the iostream class. Similar to other stream-based classes, StringStream in C++ allows performing insertion, extraction, and other operations. It is commonly used in parsing inputs and converting strings to numbers, and vice-versa.
To use stringstream, we need to include sstream header file.
stringstreams are primarily there for convenience and type-safety, not speed. The stream will collect the input and then eventually call strtold for the conversion. Makes it hard to be any faster!
To use stringstream class in the C++ program, we have to use the header <sstream>. For Example, the code to extract an integer from the string would be: string mystr(“2019”); int myInt; stringstream (mystr)>>myInt; Here we declare a string object with value “2019” and an int object “myInt”.
You can change the floating-point precision of a stringstream
as follows:
double num = 2.25149;
std::stringstream ss(stringstream::in | stringstream::out);
ss << std::setprecision(5) << num << endl;
ss << std::setprecision(4) << num << endl;
Output:
2.2515
2.251
Note how the numbers are also rounded when appropriate.
For anyone who gets "error: ‘setprecision’ is not a member of ‘std’
" you must #include <iomanip>
else setprecision(17)
will not work!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With