Output Numbers with Thousands Separator

by Jun 6, 1996

 Technical Information Database

TI2183C.txt   Output Numbers with Thousands Separator
Category   :General
Platform    :All
Product    :C/C++  All

Description:
How do I output comma-formatted numbers such as 1,000,000 with
C++ IOStreams?  As common as this would seem, C++ IOStreams have
no support for this.  The function shown in the code sample below
serves two purposes: it converts the long to a string and inserts
commas every three digits.  Adding the commas during the
conversion is much easier than converting the long to a string
using sprintf() and then modifying the string.
For new programmers, this code is an excellent example use of
the modulus operator to reverse a string.  The reversing
algorithm is almost identical to the generic reverse() function
in the Standard Template Library.
#include 
const char *commaStr(unsigned long number)
{
  const int size = 15;    // max number of digits
  static char str[size];  // string to return
  char *ptr1, *ptr2;      // place holders
  char tempStr[size];     // workplace
  int counter = 0;        // three's counter
  ptr1 = tempStr;
  do {
    // grab rightmost digit and add value of character zero
    *ptr1++ = (char)(number % 10) + '0';
    // strip off rightmost digit
    number /= 10;
    // if moved over three digits insert comma into string
    if (number &&  !(++counter % 3))
      *ptr1++ = ',';
    // continue until number equal zero
  } while(number);
  // this loop reverses characters in a string
  for( --ptr1, ptr2 = str; ptr1 >= tempStr; --ptr1)
    *ptr2++ = *ptr1;
  // add the zero string terminator
  *ptr2 = '0';
  return str;
}
// simple main to test function
int main() {
   cout <<'s "Toolbox".  If you're
new to programming, it will be worth your time to run the code
in the debugger and watch how it works.  Use
Debug|Evaluate|Modify to see how the modulus works.  Then
inspect the pointer in the reverse code to understand how it
accomplishes its task.
CAVEATS
=======
N/A
BIBLIOGRAPHY
============
N/A


Reference:


7/2/98 10:40:36 AM
 

Article originally contributed by