c++floating-pointprecisioniomanip

Formatting floats: returning to default


I am running into a formatting issue on floating-point values, in the sense of returning to "default formatting". Say I have 2 floats:

float f1 = 3.0f, f2 = 1.5f;
std::cout << f1 << " - " << f2 << "\n";

will show these as: 3 - 1.5

Now, for some reason, I need to set precision on std::cout (for other printing):

cout << std::precision(2);

If I print again my two floats, this will lead to: 3.00 - 1.50

Now I want to get back to default formatting. Until C++11 this seems to be difficult (or was it ?). But, thanks, I now got this new flag: std::defaultfloat. Lets try:

std::cout << std::defaultfloat << f1 << " - " << f2;

will print: 3 - 1.50. Fine.

Oh, but wait. Say I have instead:

float f1 = 444.0f, f2 = 444.5f;

Default printing will show: 444 - 444.5

Setting precision (and "fixed"):

cout << std::precision(2) << std::fixed;

will show: 444.00 - 444.50

But returning to "default":

std::cout << std::defaultfloat << f1 << " - " << f2;

will print: 4.4e+02 - 4.4e+02 (automatic switching to scientific format). And, in case you wonder, appending the "fixed" flag will keep the previously assigned precision, thus not returning back to original setting.

Question: How do I get back to the default mode ?

Here is the full code demonstrating the issue (also available as live code):

int main()
{
    float f1 = 444.5f, f2=443.0f;
    std::cout << f1 << " - " << f2 << "\n";
    std::cout << std::fixed << std::setprecision(2);
    std::cout << f1 << " - " << f2 << "\n";
    std::cout << std::defaultfloat;
    std::cout << f1 << " - " << f2 << "\n";
}

And the result:

444.5 - 443
444.50 - 443.00
4.4e+02 - 4.4e+02

Solution

  • std::defaultfloat doesn't reset the precision. (Don't ask me why). You could reset that to the default which is defined as 6:

    std::cout << std::defaultfloat << std::setprecision(6) << f1 << " - " << f2;
    

    Alternatively you could save the entire stream state before the operation and restore it after; see this thread for that.