Home:ALL Converter>Setting minimum number of decimal places for std::ostream precision

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

Ask Time:2010-03-22T10:04:05         Author:Phil Boltt

Json Formatter

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!

Author:Phil Boltt,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/2489627/setting-minimum-number-of-decimal-places-for-stdostream-precision
Sameer :

cout << setprecision(1) << fixed << d << endl;\n\n\nUsed fixed after setprecision.\n\nEdit: This is what you want. It would change precision based on d.\n\ncout << setprecision(d?9:1) << fixed << d << endl;\n",
2010-03-22T02:11:55
yy