home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / snip9707.zip / COMMAFMT.C < prev    next >
C/C++ Source or Header  |  1997-07-05  |  2KB  |  92 lines

  1. /* +++Date last modified: 05-Jul-1997 */
  2.  
  3. /*
  4. **  COMMAFMT.C
  5. **
  6. **  Public domain by Bob Stout, bug fixes by Mark Kamradt
  7. **
  8. **  Notes:  1. Use static buffer to eliminate error checks on buffer overflow
  9. **             and reduce code size.
  10. **          2. By making the numeric argument a long and prototyping it before
  11. **             use, passed numeric arguments will be implicitly cast to longs
  12. **             thereby avoiding int overflow.
  13. **          3. Use the thousands grouping and thousands separator from the
  14. **             ANSI locale to make this more robust.
  15. */
  16.  
  17. #include <string.h>
  18. #include "numcnvrt.h"
  19.  
  20. size_t commafmt(char   *buf,            /* Buffer for formatted string  */
  21.                 int     bufsize,        /* Size of buffer               */
  22.                 long    N)              /* Number to convert            */
  23. {
  24.       int len = 1, posn = 1, sign = 1;
  25.       char *ptr = buf + bufsize - 1;
  26.  
  27.       if (2 > bufsize)
  28.       {
  29. ABORT:      *buf = NUL;
  30.             return 0;
  31.       }
  32.  
  33.       *ptr-- = NUL;
  34.       --bufsize;
  35.       if (0L > N)
  36.       {
  37.             sign = -1;
  38.             N = -N;
  39.       }
  40.  
  41.       for ( ; len <= bufsize; ++len, ++posn)
  42.       {
  43.             *ptr-- = (char)((N % 10L) + '0');
  44.             if (0L == (N /= 10L))
  45.                   break;
  46.             if (0 == (posn % 3))
  47.             {
  48.                   *ptr-- = ',';
  49.                   ++len;
  50.             }
  51.             if (len >= bufsize)
  52.                   goto ABORT;
  53.       }
  54.  
  55.       if (0 > sign)
  56.       {
  57.             if (len >= bufsize)
  58.                   goto ABORT;
  59.             *ptr-- = '-';
  60.             ++len;
  61.       }
  62.  
  63.       memmove(buf, ++ptr, len + 1);
  64.       return (size_t)len;
  65. }
  66.  
  67. #ifdef TEST
  68.  
  69. #include <stdio.h>
  70. #include <stdlib.h>
  71.  
  72. #ifdef __WATCOMC__
  73.  #pragma off (unreferenced);
  74. #endif
  75. #ifdef __TURBOC__
  76.  #pragma argsused
  77. #endif
  78.  
  79. main(int argc, char *argv[])
  80. {
  81.       size_t len;
  82.       char buf[20];
  83.       long N;
  84.  
  85.       N = strtol(argv[1], NULL, 10);
  86.       len = commafmt(buf, 20, N);
  87.       printf("%s converts to %s and returned %d\n", argv[1], buf, len);
  88.       return EXIT_SUCCESS;
  89. }
  90.  
  91. #endif /* TEST */
  92.