How can I change the precision of printing with the stl?
I want to print numbers to a file using the stl with the number of decimal places, rather than overall precision.
So, if I do this:
int precision = 16;
std::vector<double> thePoint(3);
thePoint[0] = 86.3671436;
thePoint[1] = -334.8866574;
thePoint[2] = 24.2814;
ofstream file1(tempFileName, ios::trunc);
file1 << std::setprecision(precision)
<< thePoint[0] << "\\"
<< thePoint[1] << "\\"
<< thePoint[2] << "\\";
I'll get numbers like this:
86.36714359999999\-334.8866574\24.28140258789063
What I want is this:
86.37\-334.89\24.28
In other words开发者_Python百科, truncating at two decimal points. If I set precision to be 4, then I'll get
86.37\-334.9\24.28
ie, the second number is improperly truncated.
I do not want to have to manipulate each number explicitly to get the truncation, especially because I seem to be getting the occasional 9 repeating or 0000000001 or something like that that's left behind.
I'm sure there's something obvious, like using the printf(%.2f) or something like that, but I'm unsure how to mix that with the stl << and ofstream.
Use std::fixed , this should work for you.
file1 << std::fixed << std::setprecision(precision)
<< thePoint[0] << "\\"
<< thePoint[1] << "\\"
<< thePoint[2] << "\\";
Try
file1 << std::setiosflags(ios::fixed) << std::setprecision(precision)
which sets fixed-point format instead of floating-point.
(By the way, this is not STL. It's iostream.)
…Oh! I think Kumar bettered me with std::fixed
.
精彩评论