Commit | Line | Data |
---|---|---|
c99ed8cf BJ |
1 | /* @(#)gcvt.c 4.1 (Berkeley) %G% */ |
2 | /* | |
3 | * gcvt - Floating output conversion to | |
4 | * minimal length string | |
5 | */ | |
6 | ||
7 | char *ecvt(); | |
8 | ||
9 | char * | |
10 | gcvt(number, ndigit, buf) | |
11 | double number; | |
12 | char *buf; | |
13 | { | |
14 | int sign, decpt; | |
15 | register char *p1, *p2; | |
16 | register i; | |
17 | ||
18 | p1 = ecvt(number, ndigit, &decpt, &sign); | |
19 | p2 = buf; | |
20 | if (sign) | |
21 | *p2++ = '-'; | |
22 | for (i=ndigit-1; i>0 && p1[i]=='0'; i--) | |
23 | ndigit--; | |
24 | if (decpt >= 0 && decpt-ndigit > 4 | |
25 | || decpt < 0 && decpt < -3) { /* use E-style */ | |
26 | decpt--; | |
27 | *p2++ = *p1++; | |
28 | *p2++ = '.'; | |
29 | for (i=1; i<ndigit; i++) | |
30 | *p2++ = *p1++; | |
31 | *p2++ = 'e'; | |
32 | if (decpt<0) { | |
33 | decpt = -decpt; | |
34 | *p2++ = '-'; | |
35 | } else | |
36 | *p2++ = '+'; | |
37 | *p2++ = decpt/10 + '0'; | |
38 | *p2++ = decpt%10 + '0'; | |
39 | } else { | |
40 | if (decpt<=0) { | |
41 | if (*p1!='0') | |
42 | *p2++ = '.'; | |
43 | while (decpt<0) { | |
44 | decpt++; | |
45 | *p2++ = '0'; | |
46 | } | |
47 | } | |
48 | for (i=1; i<=ndigit; i++) { | |
49 | *p2++ = *p1++; | |
50 | if (i==decpt) | |
51 | *p2++ = '.'; | |
52 | } | |
53 | if (ndigit<decpt) { | |
54 | while (ndigit++<decpt) | |
55 | *p2++ = '0'; | |
56 | *p2++ = '.'; | |
57 | } | |
58 | } | |
59 | if (p2[-1]=='.') | |
60 | p2--; | |
61 | *p2 = '\0'; | |
62 | return(buf); | |
63 | } |