Setting minimum number of decimal places for std::ostream precision

Phil Boltt picture Phil Boltt · Mar 22, 2010 · Viewed 7.5k times · Source

Is there a way to set the "minimum" number of decimal places that a std::ostream will output?

For example, say I have two unknown double variables that I want to print (values added here for the sake of illustration):

double a = 0;
double b = 0.123456789;

I can set my maximum decimal precision so that I output b exactly

std::cout << std::setprecision(9) << b << std::endl;
>>> 0.123456789

Is there a way to set a "minimum" precision (a minimum number of decimal places), while retaining the "maximum" precision, so that

std::cout << a << std::endl << b << std::endl;

yields

0.0
0.123456789

not

0
0.123456789

?

Thanks! Phil


the short answer to this is "No". The stream has only one precision setting, with no facility to differentiate between maximum and minimum precision. Thanks all for your generous advice!

Answer

Sameer picture Sameer · Mar 22, 2010
cout << setprecision(1) << fixed << d << endl;

Used fixed after setprecision.

Edit: This is what you want. It would change precision based on d.

cout << setprecision(d?9:1) << fixed << d << endl;