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

  1. /* +++Date last modified: 05-Jul-1997 */
  2.  
  3. /*
  4. **  COMMAFLT.C - Format a double using commas as thousands separators
  5. **               and a specified number of significant fractional digits.
  6. **
  7. **  public domain by Bruce Wedding and Kurt Kuzba
  8. */
  9. #include <stdio.h>
  10.  
  11. #include "numcnvrt.h"
  12. #include "snip_str.h"
  13.  
  14. char *comma_float( double num, char *buf, int dec)
  15. {
  16.       char tmp[80];
  17.       int bf = 0, cm = 0, tm = 9 - dec + (!dec);
  18.  
  19.       sprintf(tmp, "%.9f", num);
  20.       strrev(tmp);
  21.       if(dec)
  22.       {
  23.             while( (buf[bf++] = tmp[tm++]) != '.')
  24.                   ;
  25.             while((buf[bf++] = tmp[tm++]) != 0)
  26.             {
  27.                   if(++cm % 3 == 0 && tmp[tm])
  28.                         buf[bf++] = ',';
  29.             }
  30.       }
  31.       return strrev(buf);
  32. }
  33.  
  34. #ifdef TEST
  35.  
  36. #include <stdio.h>
  37.  
  38. int main( void )
  39. {
  40.       int i;
  41.       char result[80];
  42.       double num[10] = {
  43.             1.98765,       12.98765,       123.98765,
  44.             1234.98765,    12345.98765,    123456.98765,
  45.             1234567.98765, 12345678.98765, 123456789.98765,
  46.             1234567890.98765  };
  47.  
  48.       for ( i = 0; i < 10; i++ )
  49.             printf("Before: %-24.5f After: %s \n",
  50.                   num[i], comma_float(num[i], result, 6));
  51.       return 0;
  52. }
  53.  
  54. #endif /* TEST */
  55.