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

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