1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
|
#include <iostream>
#include <string>
#include <sstream>
#include <iomanip>
#include <boost/format.hpp>
std::string format( double d, int place )
{
std::ostringstream ss;
ss << std::fixed << std::setprecision(place) << d ;
return ss.str() ;
}
struct format_a
{
format_a( double d, int place ) : value(d), prec(place) {}
const double value ;
const int prec ;
};
template < typename OSTREAM >
OSTREAM& operator<< ( OSTREAM& stm, const format_a& fmt )
{ return stm << std::fixed << std::setprecision(fmt.prec) << fmt.value ; }
struct format_b
{
explicit format_b( int place, int w = 0, char f = ' ' )
: prec(place), width(w), fill(f) {}
template < typename T > format_b& operator% ( const T& v )
{
std::ostringstream ss;
ss << std::fixed << std::setprecision(prec)
<< std::setw(width) << std::setfill(fill) << v ;
chars_out += ss.str() ;
return *this ;
}
const int prec ;
const int width ;
const char fill ;
std::string chars_out ;
};
template < typename OSTREAM >
OSTREAM& operator<< ( OSTREAM& stm, const format_b& fmt )
{ for( char c : fmt.chars_out ) stm << stm.widen(c) ; return stm ; }
int main ()
{
std::cout << format( .0123456789, 2 ) << '\n' ;
std::cout << format( 11.1123456789, 5 ) << '\n' ;
std::cout << format_a( 1234.2123456789, 3 ) << '\n' ;
std::wcout << format_a( 1234.3123456789, 2 ) << '\n' ;
std::cout << format_b(3) % 1234.2123456789 << '\n' ;
std::wcout << format_b( 2, 9 ) % "values:" % 999.999 % 1234.3123456789 % '\n' ;
double x = 7.40200133400;
std::cout << boost::format("%1$.2f")%x << '\n' ;
}
|