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