views:

57

answers:

2

This might be a repeat, but my google-fu failed to find it.

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[0] = -334.8866574;
thePoint[0] = 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, 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.

+2  A: 

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.

Jon Reid
How is it Not STL? iostream is one of the standard template libraries....
SoapBox
Just because something uses templates doesn't make it STL. Follow the links and you will find they are radically different.
Jon Reid
+5  A: 

Use std::fixed , this should work for you.

 file1 << std::fixed << std::setprecision(precision)
     << thePoint[0]  << "\\"
     << thePoint[1]  << "\\"
     << thePoint[2] << "\\";
kumar
That's it, thanks!
mmr