xref: /original-bsd/lib/libcompat/4.3/gcvt.c (revision 514cbc2d)
1 /*-
2  * Copyright (c) 1991, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * %sccs.include.proprietary.c%
6  */
7 
8 #if defined(LIBC_SCCS) && !defined(lint)
9 static char sccsid[] = "@(#)gcvt.c	8.1 (Berkeley) 06/04/93";
10 #endif /* LIBC_SCCS and not lint */
11 
12 /*
13  * gcvt  - Floating output conversion to
14  * minimal length string
15  */
16 
17 char	*ecvt();
18 
19 char *
20 gcvt(number, ndigit, buf)
21 double number;
22 char *buf;
23 {
24 	int sign, decpt;
25 	register char *p1, *p2;
26 	register i;
27 
28 	p1 = ecvt(number, ndigit, &decpt, &sign);
29 	p2 = buf;
30 	if (sign)
31 		*p2++ = '-';
32 	for (i=ndigit-1; i>0 && p1[i]=='0'; i--)
33 		ndigit--;
34 	if (decpt >= 0 && decpt-ndigit > 4
35 	 || decpt < 0 && decpt < -3) { /* use E-style */
36 		decpt--;
37 		*p2++ = *p1++;
38 		*p2++ = '.';
39 		for (i=1; i<ndigit; i++)
40 			*p2++ = *p1++;
41 		*p2++ = 'e';
42 		if (decpt<0) {
43 			decpt = -decpt;
44 			*p2++ = '-';
45 		} else
46 			*p2++ = '+';
47 		*p2++ = decpt/10 + '0';
48 		*p2++ = decpt%10 + '0';
49 	} else {
50 		if (decpt<=0) {
51 			if (*p1!='0')
52 				*p2++ = '.';
53 			while (decpt<0) {
54 				decpt++;
55 				*p2++ = '0';
56 			}
57 		}
58 		for (i=1; i<=ndigit; i++) {
59 			*p2++ = *p1++;
60 			if (i==decpt)
61 				*p2++ = '.';
62 		}
63 		if (ndigit<decpt) {
64 			while (ndigit++<decpt)
65 				*p2++ = '0';
66 			*p2++ = '.';
67 		}
68 	}
69 	if (p2[-1]=='.')
70 		p2--;
71 	*p2 = '\0';
72 	return(buf);
73 }
74