home *** CD-ROM | disk | FTP | other *** search
/ Monster Media 1994 #1 / monster.zip / monster / PROG_C / SNPD9404.ZIP / ENG.C < prev    next >
C/C++ Source or Header  |  1994-04-03  |  1KB  |  51 lines

  1. /* ENG.C - Format floating point in engineering notation          */
  2. /* Released to public domain by author, David Harmon, Jan. 1994   */
  3.  
  4. #include <stdio.h>
  5.  
  6. char *eng(double value, int places)
  7. {
  8.       const char * const prefixes[] = {
  9.             "a", "f", "p", "n", "µ", "m", "", "k", "M", "G", "T"
  10.             };
  11.       int p = 6;
  12.       static char result[30];
  13.       char *res = result;
  14.  
  15.       if (value < 0.)
  16.       {
  17.             *res++ = '-';
  18.             value = -value;
  19.       }
  20.       while (value != 0 && value < 1. && p > 0)
  21.       {
  22.             value *= 1000.;
  23.             p--;
  24.       }
  25.       while (value != 0 && value > 1000. && p < 10 )
  26.       {
  27.             value /= 1000.;
  28.             p++;
  29.       }
  30.       if (value > 100.)
  31.             places--;
  32.       if (value > 10.)
  33.             places--;
  34.       sprintf(res, "%.*f %s", places-1, value, prefixes[p]);
  35.       return result;
  36. }
  37.  
  38. #ifdef TEST
  39.  
  40. #include <stdio.h>
  41.  
  42. main()
  43. {
  44.       double w;
  45.  
  46.       for (w = 1e-19; w < 1e16; w *= 42)
  47.             printf(" %g W = %sW\n", w, eng(w, 3));
  48.       return 0;
  49. }
  50. #endif
  51.