home *** CD-ROM | disk | FTP | other *** search
/ The C Users' Group Library 1994 August / wc-cdrom-cusersgrouplibrary-1994-08.iso / vol_100 / 161_01 / fround.c < prev    next >
C/C++ Source or Header  |  1985-08-29  |  1KB  |  52 lines

  1. /* fround - round double x to precision p, n significant digits
  2.  * uses static string for result - not re-entrant
  3.  * fround is an accomodation for K+R-level printf which lacks %.*e or %g
  4.  * slow, fat version - uses sprintf
  5.  */
  6. #include <stdio.h>
  7. char *fround(x, p, n)
  8.     double x;
  9.     short p;
  10.     short n;
  11.     {
  12.     double y;
  13.     double log10();
  14.     short digs;
  15.     short nlog;
  16.     static char s[40] = {0};
  17.     char fmt[20];
  18.  
  19.     sprintf(fmt, "%%.%de", n-1);
  20.     sprintf(s, fmt, x);
  21.     sscanf(s, "%lf", &y);
  22.     if (y == 0)
  23.         nlog = 0;
  24.     else
  25.         nlog = log10(y);
  26.     if (nlog < 0)
  27.         --nlog;
  28.     digs = n - nlog - 1;
  29.     if (digs < 0)
  30.         digs = 0;
  31.     else if (digs > p)
  32.         digs = p;
  33.     sprintf(fmt, "%%.%df", digs);
  34.     sprintf(s, fmt, y);
  35.     if (digs == 0)
  36.         strcat(s, ".");
  37.     while (digs++ < p)
  38.         strcat(s, " ");
  39.     return (s);
  40.     }
  41. #ifdef TRYMAIN
  42. main()
  43.     {
  44.     short m;
  45.  
  46.     for (m = 1; m <= 5; ++m)
  47.         printf("fround(123.57, 2, %d) = %s;\n", m, fround(123.57, 2, m));
  48.     for (m = 1; m <= 5; ++m)
  49.         printf("fround(.013579, 5, %d) = %s;\n", m, fround(.013579, 5, m));
  50.     }
  51. #endif
  52.