Alex Rivera | Logout

Portable printing of exponent of a double to C++ iostreams

Asked 2012-02-10T10:37:04.987
15

I want to print a double value to std::cout portably (GCC, clang, MSVC++) such that the output is the same on all platforms.

I have a problem with the formatting of the exponent. The following program

#include <iostream>
int main()
{
    std::cout << 0.1e-7 << std::endl;
    return 0;
}

Has this output with GCC:

1e-08

and the following output with MSVC

1e-008

How can I make both outputs the same?

I'm sorry if this is a dumb question but I have not found an answer so far. All formatting seems to evolve around the formatting of everything before the mantissa...

EDIT: The output of GCC is 1e-08 not 1e-8 (as originally stated) so it is conforming. Sorry for the confusion.

EDIT2: Actually renamed "mantissa" to "exponent" following Dietmar's remark. There also is a section on Wikipedia on mantissa vs. significant.

Edit
Report

1 Answer

3

While Dietmar's answer is the clean and probably only really portable answer, I accidentally found a quick-and-dirty answer: MSVC provides the _set_output_format function which you can use to switch to "print exponent as two digits".

The following RAII class can be instantiated in your main() function to give you the same behaviour of GCC, CLANG and MSVC.

class ScientificNotationExponentOutputNormalizer
{
public:
    unsigned _oldExponentFormat;

    ScientificNotationExponentOutputNormalizer() : _oldExponentFormat(0)
    {
#ifdef _MSC_VER
        // Set scientific format to print two places.
        unsigned _oldExponentFormat = _set_output_format(_TWO_DIGIT_EXPONENT);
#endif
    }

    ~ScientificNotationExponentOutputNormalizer()
    {
#ifdef _MSC_VER
        // Enable old exponent format.
        _set_output_format(_oldExponentFormat);
#endif
    }
};
answered 2012-02-10T12:16:15.837

Your Answer