Correct Way to set maximum double precision for ostringstream
By referring to
How开发者_开发百科 do I print a double value with full precision using cout?
and
What is the meaning of numeric_limits<double>::digits10
I am slightly confused.
Shall I used :
ss.precision(std::numeric_limits<double>::digits10);
or
ss.precision(std::numeric_limits<double>::digits10 + 2);
to get maximum double precision?
it depend on number of "decimal component" you have in data.
std::numeric_limits::digits10 will give the maximum number of "floating component"
ios_base::precision specifies the number of digits (decimal + float components) to display.
if your decimal component is always less than 100 (-99 to 99), code below always give maximum precision.
ss.precision(std::numeric_limits<double>::digits10 + 2);
According to What is the meaning of numeric_limits<double>::digits10, specifically the highest voted answer, std::numericlimits<double>::digits10
is:
the maximum number of digits you can represent without loss of precision.
That means if you set ss.precision to that, these floating point digits will be accurate; if you set it to that +2 you will still display that+2 digits but the last two aren't guaranteed to be accurately calculated.
For arbitray precision, if that's what you need, take a look at mpir, gmp, mpfr
精彩评论