Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Floating point format for std::ostream

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.

like image 862
Jive Dadson Avatar asked Aug 16 '12 14:08

Jive Dadson


2 Answers

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; 
like image 193
Kiril Kirov Avatar answered Sep 20 '22 02:09

Kiril Kirov


std::cout << boost::format("%11.6f") % my_double; 

You have to #include <boost\format.hpp>

like image 34
Andrey Avatar answered Sep 21 '22 02:09

Andrey