Question

I am getting a bit frustrated by my inability to get a double to print (to stdout) using the desired number of decimal places.

My current code looks like this:

void SomeFunction(vector<string> argv, ostream& oss){
   SomeClass ClassMembers ;
   string directory = argv.at(2) ;
   // specialized code that opens "FileName", defined by "directory"
   ClassMembers.GetValues(FileName) ;
   oss << ClassMembers.SomeNumber << endl ;
}

That is the general idea. The problem is that I cannot get ClassMember.SomeNumber to print out to, say, 5 decimal places by using:

oss << precision(5) ;

Note that "SomeNumber" is a class member that is declared as double.

It always gives me the number of decimal places that the parsed number found in the body of FileName has.

What am I doing wrong?

Thanks!

Was it helpful?

Solution

oss.precision(5); That should do it, according to this page.

So what you would want to do is this:

oss.precision(5);
oss << ClassMembers.SomeNumber << endl ;

Mind you the "precision" implies the maximum number of digits to display (not the minimum, so it will not include leading/trailing zeros or spaces).

If you want the precise number of decimal places to be used, use std::fixed beforehand, like so:

oss.precision(5);
oss << std::fixed << ClassMembers.SomeNumber << endl;

OTHER TIPS

You might try to use std::fixed in combination. There can't be any more unseen digits, than have being parsed from your input.

Set the flag for floatfield, and you should be able to get as many digits after the decimal place as you want.

#include<iomanip>
//...
oss.setf(ios::fixed,ios::floatfield);
oss.precision(5);
oss << ClassMembers.SomeNumber << endl;

If, for example, we were to use this method and print the value 12345.67 instead of ClassMembers.SomeNumber, the output would be:

12345.67000

You may try this..

oss << setiosflags(ios::fixed);
oss << setprecision(5);
oss << ClassMembers.SomeNumber << endl ;

By using setprecision(5) alone, it includes the numbers before decimal place.

E.g: 1234.777 become 1234.8

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top