double val = 0.1;
std::stringstream ss;
ss << val;
std::string strVal= ss.str();
In the Visual Studio debugger, val
has the value 0.
The problem occurs at the stream insertion ss << 0.1;
rather than at the conversion to string. If you want non-default precision you need to specify this prior to inserting the double:
ss << std::setprecision(17) << val;
On my computer, if I just use setprecision(16)
I still get "0.1"
rather than "0.10000000000000001"
. I need a (slightly bogus) precision of 17 to see that final 1.
Addendum
A better demonstration arises with a value of 1.0/3.0. With the default precision you get a string representation of "0.333333"
. This is not the string equivalent of a double precision 1/3. Using setprecision(16)
makes the string "0.3333333333333333"
; a precision of 17 yields "0.33333333333333331"
.