How to change print accuracy using stl?

I want to print numbers in a file using stl with the number of decimal places, and not general accuracy.

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 will get these numbers:

86.36714359999999\-334.8866574\24.28140258789063

I want it:

86.37\-334.89\24.28

In other words, truncation at two decimal points. If I set the accuracy to 4, then I will get

86.37\-334.9\24.28

those. the second number is incorrectly truncated.

I don't want to manipulate each number explicitly to get a truncation, especially since I seem to get random 9 repetitions or 0000000001 or something similar that remains.

I'm sure there is something obvious, like using printf (%. 2f) or something like that, but I'm not sure how to mix this with stl <and stream.

+3
source share
2 answers

std:: fixed, .

 file1 << std::fixed << std::setprecision(precision)
     << thePoint[0]  << "\\"
     << thePoint[1]  << "\\"
     << thePoint[2] << "\\";
+7

Try

file1 << std::setiosflags(ios::fixed) << std::setprecision(precision)

.

(, STL. iostream.)

... ! , std::fixed.

+2

Source: https://habr.com/ru/post/1737462/


All Articles