Listing 11 Uses prepend and preprintf to format numbers with comma separators

/* commas.c:    Converts a number into a string with commas */

#include <stdio.h>

#define BASE 10
#define GROUP 3

/* Need space to hold the digits of an unsigned long,
 * intervening commas and a null byte. It depends on
 * BASE and GROUP above (but logarithmically, not
 * as a constant. so we must define it manually here)
 */
#define MAXTEXT 14      /* For BASE = 10 */

int prepend(char *, unsigned, char *);
int preprintf(char *, unsigned, char *, ...);

char *commas(unsigned long amount)
{
   short offset = MAXTEXT-1,   /* where the string "starts"  */
        place;                /* the power of BASE for      */
                          /* current digit              */
   static char text[MAXTEXT];
   
   text[offset] = '\0';
   
   /* Push digits right-to-left with commas */
   for (place = 0; amount > 0; ++place)
   {
      if (place % GROUP == 0 && place > 0)
         offset = prepend(text,offset,",");
      offset = preprintf(text,offset,"%x",amount % BASE);
      amount /= BASE;
   }
   return (offset >= 0) ? text + offset : NULL;
}

main()
{
   puts(commas(1));
   puts(commas(12));
   puts(commas(123));
   puts(commas(1234));
   puts(commas(12345));
   puts(commas(123456));
   puts(commas(1234567));
   puts(commas(12345678));
   puts(commas(123456789));
   puts(commas(1234567890));
   return 0;
}

/* Output:
1
12
123
1,234
12,345
123,456
1,234,567
12,345.678
123,456,789
1,234,567,890
*/

/* End of File */