Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to specifiy the number of decimal places using "ostream"

Tags:

c++

ostream

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!

like image 734
da5id Avatar asked Dec 13 '25 23:12

da5id


1 Answers

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;
like image 167
Gurgadurgen Avatar answered Dec 15 '25 11:12

Gurgadurgen