Floating point format for std::ostream

Jive Dadson picture Jive Dadson · Aug 16, 2012 · Viewed 67.8k times · Source

How do I do the following with std::cout?

double my_double = 42.0;
char str[12];
printf_s("%11.6lf", my_double); // Prints " 42.000000"

I am just about ready to give up and use sprintf_s.

More generally, where can I find a reference on std::ostream formatting that lists everything in one place, rather than spreading it all out in a long tutorial?

EDIT Dec 21, 2017 - See my answer below. It uses features that were not available when I asked this question in 2012.

Answer

Kiril Kirov picture Kiril Kirov · Aug 16, 2012
std::cout << std::fixed << std::setw( 11 ) << std::setprecision( 6 ) << my_double;

You need to add

#include <iomanip>

You need stream manipulators

You may "fill" the empty places with whatever char you want. Like this:

std::cout << std::fixed << std::setw( 11 ) << std::setprecision( 6 ) 
          << std::setfill( '0' ) << my_double;