Download this source file


// Effector2.cpp - create a "fmt" manipulator that will format
// numbers such as "dddd.ddd" as "d,ddd.dd".  Note that to do this
// well would require looking at the current locale for the proper
// decimal point character, digit-group seperator character,
// and digit-group size.  (This example uses ".", ",", and "3".
//
// Written by Wayne Pollock, Tampa FL, 1999.

#include <iostream>
#include <iomanip>
#include <sstream>
#include <cstring>
// #include <locale>

using namespace std;

class fmt
{
   char rep[64];

 public:
   fmt (double number, int num_places = 2);
   friend ostream& operator<< (ostream&, const fmt&);
};

fmt::fmt (double number, int num_of_places)
{  char buf[64] = "";
   strstream raw(buf, sizeof(buf), ios::in | ios::out);
   ostrstream os(rep, sizeof(rep));
   // Convert number to a string:
   raw.setf(ios::fixed);   // don't use scientific notation!
   raw << setprecision(num_of_places) << number << ends;
   int num_digits_on_left = strlen(buf) - (num_of_places + 1);
   int i = 0, j = 0;
   if ( buf[0] == '-' )
   {  rep[i++] = buf[j++];
      --num_digits_on_left;
   }
   try
   {  if (num_digits_on_left <= 3)   throw 0;  // No further formatting needed.
      int k = num_digits_on_left % 3;  // k = # of digits to left of 1st comma.
      if ( k )
      {  for ( ; k>0; --k )   // copy first k digits,
         rep[i++] = buf[j++];
         rep[i++] = ',';      // then add a comma.
      }
      while ( buf[j] != '.' )    // Print remaining digits 3 at a time,
      {  for ( int k=0; k<3; ++k )
         rep[i++] = buf[j++];
         rep[i++] = ',';  // then add a comma.
      }
      rep[--i] = buf[j++];  // Overwrite the last comma with a decimal point.
      ++i;
   }
   catch ( int ) {}    // Exceptions can replace "goto"!
   while ( buf[j] != 0 )  rep[i++] = buf[j++];
   rep[i] = 0;
}

inline ostream& operator<< ( ostream& out, const fmt& f )
{  out << f.rep; return out;  }


int main ()
{  double num;
   for ( ;; )
   {  cout << "\nEnter a number (^Z to Exit): ";
      if ( !(cin >> num) )   break;
      cout << "\n\tYour number formatted looks like this: ";
      cout << fmt(num) << endl;
   }
   return 0;
}