File: eng.c

package info (click to toggle)
c-cpp-reference 2.0.2-6
  • links: PTS
  • area: main
  • in suites: etch, etch-m68k, lenny
  • size: 8,012 kB
  • ctags: 4,612
  • sloc: ansic: 26,960; sh: 11,014; perl: 1,854; cpp: 1,324; asm: 1,239; python: 258; makefile: 115; java: 77; awk: 34; csh: 9
file content (50 lines) | stat: -rwxr-xr-x 1,108 bytes parent folder | download | duplicates (5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
/* ENG.C - Format floating point in engineering notation          */
/* Released to public domain by author, David Harmon, Jan. 1994   */

#include <stdio.h>

char *eng(double value, int places)
{
      const char * const prefixes[] = {
            "a", "f", "p", "n", "", "m", "", "k", "M", "G", "T"
            };
      int p = 6;
      static char result[30];
      char *res = result;

      if (value < 0.)
      {
            *res++ = '-';
            value = -value;
      }
      while (value != 0 && value < 1. && p > 0)
      {
            value *= 1000.;
            p--;
      }
      while (value != 0 && value > 1000. && p < 10 )
      {
            value /= 1000.;
            p++;
      }
      if (value > 100.)
            places--;
      if (value > 10.)
            places--;
      sprintf(res, "%.*f %s", places-1, value, prefixes[p]);
      return result;
}

#ifdef TEST

#include <stdio.h>

main()
{
      double w;

      for (w = 1e-19; w < 1e16; w *= 42)
            printf(" %g W = %sW\n", w, eng(w, 3));
      return 0;
}
#endif