xref: /original-bsd/lib/libc/stdio/vfprintf.c (revision e59fb703)
1 /*-
2  * Copyright (c) 1990 The Regents of the University of California.
3  * All rights reserved.
4  *
5  * This code is derived from software contributed to Berkeley by
6  * Chris Torek.
7  *
8  * %sccs.include.redist.c%
9  */
10 
11 #if defined(LIBC_SCCS) && !defined(lint)
12 static char sccsid[] = "@(#)vfprintf.c	5.48 (Berkeley) 07/19/91";
13 #endif /* LIBC_SCCS and not lint */
14 
15 /*
16  * Actual printf innards.
17  *
18  * This code is large and complicated...
19  */
20 
21 #include <sys/types.h>
22 #include <math.h>
23 #include <stdio.h>
24 #include <string.h>
25 #if __STDC__
26 #include <stdarg.h>
27 #else
28 #include <varargs.h>
29 #endif
30 #include "local.h"
31 #include "fvwrite.h"
32 
33 /* Define FLOATING_POINT to get floating point. */
34 #define	FLOATING_POINT
35 
36 /*
37  * Flush out all the vectors defined by the given uio,
38  * then reset it so that it can be reused.
39  */
40 static int
41 __sprint(fp, uio)
42 	FILE *fp;
43 	register struct __suio *uio;
44 {
45 	register int err;
46 
47 	if (uio->uio_resid == 0) {
48 		uio->uio_iovcnt = 0;
49 		return (0);
50 	}
51 	err = __sfvwrite(fp, uio);
52 	uio->uio_resid = 0;
53 	uio->uio_iovcnt = 0;
54 	return (err);
55 }
56 
57 /*
58  * Helper function for `fprintf to unbuffered unix file': creates a
59  * temporary buffer.  We only work on write-only files; this avoids
60  * worries about ungetc buffers and so forth.
61  */
62 static int
63 __sbprintf(fp, fmt, ap)
64 	register FILE *fp;
65 	const char *fmt;
66 	va_list ap;
67 {
68 	int ret;
69 	FILE fake;
70 	unsigned char buf[BUFSIZ];
71 
72 	/* copy the important variables */
73 	fake._flags = fp->_flags & ~__SNBF;
74 	fake._file = fp->_file;
75 	fake._cookie = fp->_cookie;
76 	fake._write = fp->_write;
77 
78 	/* set up the buffer */
79 	fake._bf._base = fake._p = buf;
80 	fake._bf._size = fake._w = sizeof(buf);
81 	fake._lbfsize = 0;	/* not actually used, but Just In Case */
82 
83 	/* do the work, then copy any error status */
84 	ret = vfprintf(&fake, fmt, ap);
85 	if (ret >= 0 && fflush(&fake))
86 		ret = EOF;
87 	if (fake._flags & __SERR)
88 		fp->_flags |= __SERR;
89 	return (ret);
90 }
91 
92 
93 #ifdef FLOATING_POINT
94 #include "floatio.h"
95 
96 #define	BUF		(MAXEXP+MAXFRACT+1)	/* + decimal point */
97 #define	DEFPREC		6
98 
99 static int cvt();
100 
101 #else /* no FLOATING_POINT */
102 
103 #define	BUF		40
104 
105 #endif /* FLOATING_POINT */
106 
107 
108 /*
109  * Macros for converting digits to letters and vice versa
110  */
111 #define	to_digit(c)	((c) - '0')
112 #define is_digit(c)	((unsigned)to_digit(c) <= 9)
113 #define	to_char(n)	((n) + '0')
114 
115 /*
116  * Flags used during conversion.
117  */
118 #define	LONGINT		0x01		/* long integer */
119 #define	LONGDBL		0x02		/* long double; unimplemented */
120 #define	SHORTINT	0x04		/* short integer */
121 #define	ALT		0x08		/* alternate form */
122 #define	LADJUST		0x10		/* left adjustment */
123 #define	ZEROPAD		0x20		/* zero (as opposed to blank) pad */
124 #define	HEXPREFIX	0x40		/* add 0x or 0X prefix */
125 
126 int
127 vfprintf(fp, fmt0, ap)
128 	FILE *fp;
129 	const char *fmt0;
130 #if tahoe
131  register /* technically illegal, since we do not know what type va_list is */
132 #endif
133 	va_list ap;
134 {
135 	register char *fmt;	/* format string */
136 	register int ch;	/* character from fmt */
137 	register int n;		/* handy integer (short term usage) */
138 	register char *cp;	/* handy char pointer (short term usage) */
139 	register struct __siov *iovp;/* for PRINT macro */
140 	register int flags;	/* flags as above */
141 	int ret;		/* return value accumulator */
142 	int width;		/* width from format (%8d), or 0 */
143 	int prec;		/* precision from format (%.3d), or -1 */
144 	char sign;		/* sign prefix (' ', '+', '-', or \0) */
145 #ifdef FLOATING_POINT
146 	char softsign;		/* temporary negative sign for floats */
147 	double _double;		/* double precision arguments %[eEfgG] */
148 	int fpprec;		/* `extra' floating precision in [eEfgG] */
149 #endif
150 	u_long _ulong;		/* integer arguments %[diouxX] */
151 	enum { OCT, DEC, HEX } base;/* base for [diouxX] conversion */
152 	int dprec;		/* a copy of prec if [diouxX], 0 otherwise */
153 	int fieldsz;		/* field size expanded by sign, etc */
154 	int realsz;		/* field size expanded by dprec */
155 	int size;		/* size of converted field or string */
156 	char *xdigs;		/* digits for [xX] conversion */
157 #define NIOV 8
158 	struct __suio uio;	/* output information: summary */
159 	struct __siov iov[NIOV];/* ... and individual io vectors */
160 	char buf[BUF];		/* space for %c, %[diouxX], %[eEfgG] */
161 	char ox[2];		/* space for 0x hex-prefix */
162 
163 	/*
164 	 * Choose PADSIZE to trade efficiency vs size.  If larger
165 	 * printf fields occur frequently, increase PADSIZE (and make
166 	 * the initialisers below longer).
167 	 */
168 #define	PADSIZE	16		/* pad chunk size */
169 	static char blanks[PADSIZE] =
170 	 {' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' '};
171 	static char zeroes[PADSIZE] =
172 	 {'0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0'};
173 
174 	/*
175 	 * BEWARE, these `goto error' on error, and PAD uses `n'.
176 	 */
177 #define	PRINT(ptr, len) { \
178 	iovp->iov_base = (ptr); \
179 	iovp->iov_len = (len); \
180 	uio.uio_resid += (len); \
181 	iovp++; \
182 	if (++uio.uio_iovcnt >= NIOV) { \
183 		if (__sprint(fp, &uio)) \
184 			goto error; \
185 		iovp = iov; \
186 	} \
187 }
188 #define	PAD(howmany, with) { \
189 	if ((n = (howmany)) > 0) { \
190 		while (n > PADSIZE) { \
191 			PRINT(with, PADSIZE); \
192 			n -= PADSIZE; \
193 		} \
194 		PRINT(with, n); \
195 	} \
196 }
197 #define	FLUSH() { \
198 	if (uio.uio_resid && __sprint(fp, &uio)) \
199 		goto error; \
200 	uio.uio_iovcnt = 0; \
201 	iovp = iov; \
202 }
203 
204 	/*
205 	 * To extend shorts properly, we need both signed and unsigned
206 	 * argument extraction methods.
207 	 */
208 #define	SARG() \
209 	(flags&LONGINT ? va_arg(ap, long) : \
210 	    flags&SHORTINT ? (long)(short)va_arg(ap, int) : \
211 	    (long)va_arg(ap, int))
212 #define	UARG() \
213 	(flags&LONGINT ? va_arg(ap, u_long) : \
214 	    flags&SHORTINT ? (u_long)(u_short)va_arg(ap, int) : \
215 	    (u_long)va_arg(ap, u_int))
216 
217 	/* sorry, fprintf(read_only_file, "") returns EOF, not 0 */
218 	if (cantwrite(fp))
219 		return (EOF);
220 
221 	/* optimise fprintf(stderr) (and other unbuffered Unix files) */
222 	if ((fp->_flags & (__SNBF|__SWR|__SRW)) == (__SNBF|__SWR) &&
223 	    fp->_file >= 0)
224 		return (__sbprintf(fp, fmt0, ap));
225 
226 	fmt = (char *)fmt0;
227 	uio.uio_iov = iovp = iov;
228 	uio.uio_resid = 0;
229 	uio.uio_iovcnt = 0;
230 	ret = 0;
231 
232 	/*
233 	 * Scan the format for conversions (`%' character).
234 	 */
235 	for (;;) {
236 		for (cp = fmt; (ch = *fmt) != '\0' && ch != '%'; fmt++)
237 			/* void */;
238 		if ((n = fmt - cp) != 0) {
239 			PRINT(cp, n);
240 			ret += n;
241 		}
242 		if (ch == '\0')
243 			goto done;
244 		fmt++;		/* skip over '%' */
245 
246 		flags = 0;
247 		dprec = 0;
248 #ifdef FLOATING_POINT
249 		fpprec = 0;
250 #endif
251 		width = 0;
252 		prec = -1;
253 		sign = '\0';
254 
255 rflag:		ch = *fmt++;
256 reswitch:	switch (ch) {
257 		case ' ':
258 			/*
259 			 * ``If the space and + flags both appear, the space
260 			 * flag will be ignored.''
261 			 *	-- ANSI X3J11
262 			 */
263 			if (!sign)
264 				sign = ' ';
265 			goto rflag;
266 		case '#':
267 			flags |= ALT;
268 			goto rflag;
269 		case '*':
270 			/*
271 			 * ``A negative field width argument is taken as a
272 			 * - flag followed by a positive field width.''
273 			 *	-- ANSI X3J11
274 			 * They don't exclude field widths read from args.
275 			 */
276 			if ((width = va_arg(ap, int)) >= 0)
277 				goto rflag;
278 			width = -width;
279 			/* FALLTHROUGH */
280 		case '-':
281 			flags |= LADJUST;
282 			goto rflag;
283 		case '+':
284 			sign = '+';
285 			goto rflag;
286 		case '.':
287 			if ((ch = *fmt++) == '*') {
288 				n = va_arg(ap, int);
289 				prec = n < 0 ? -1 : n;
290 				goto rflag;
291 			}
292 			n = 0;
293 			while (is_digit(ch)) {
294 				n = 10 * n + to_digit(ch);
295 				ch = *fmt++;
296 			}
297 			prec = n < 0 ? -1 : n;
298 			goto reswitch;
299 		case '0':
300 			/*
301 			 * ``Note that 0 is taken as a flag, not as the
302 			 * beginning of a field width.''
303 			 *	-- ANSI X3J11
304 			 */
305 			flags |= ZEROPAD;
306 			goto rflag;
307 		case '1': case '2': case '3': case '4':
308 		case '5': case '6': case '7': case '8': case '9':
309 			n = 0;
310 			do {
311 				n = 10 * n + to_digit(ch);
312 				ch = *fmt++;
313 			} while (is_digit(ch));
314 			width = n;
315 			goto reswitch;
316 #ifdef FLOATING_POINT
317 		case 'L':
318 			flags |= LONGDBL;
319 			goto rflag;
320 #endif
321 		case 'h':
322 			flags |= SHORTINT;
323 			goto rflag;
324 		case 'l':
325 			flags |= LONGINT;
326 			goto rflag;
327 		case 'c':
328 			*(cp = buf) = va_arg(ap, int);
329 			size = 1;
330 			sign = '\0';
331 			break;
332 		case 'D':
333 			flags |= LONGINT;
334 			/*FALLTHROUGH*/
335 		case 'd':
336 		case 'i':
337 			_ulong = SARG();
338 			if ((long)_ulong < 0) {
339 				_ulong = -_ulong;
340 				sign = '-';
341 			}
342 			base = DEC;
343 			goto number;
344 #ifdef FLOATING_POINT
345 		case 'e':
346 		case 'E':
347 		case 'f':
348 		case 'g':
349 		case 'G':
350 			_double = va_arg(ap, double);
351 			/* do this before tricky precision changes */
352 			if (isinf(_double)) {
353 				if (_double < 0)
354 					sign = '-';
355 				cp = "Inf";
356 				size = 3;
357 				break;
358 			}
359 			if (isnan(_double)) {
360 				cp = "NaN";
361 				size = 3;
362 				break;
363 			}
364 			/*
365 			 * don't do unrealistic precision; just pad it with
366 			 * zeroes later, so buffer size stays rational.
367 			 */
368 			if (prec > MAXFRACT) {
369 				if (ch != 'g' && ch != 'G' || (flags&ALT))
370 					fpprec = prec - MAXFRACT;
371 				prec = MAXFRACT;
372 			} else if (prec == -1)
373 				prec = DEFPREC;
374 			/*
375 			 * cvt may have to round up before the "start" of
376 			 * its buffer, i.e. ``intf("%.2f", (double)9.999);'';
377 			 * if the first character is still NUL, it did.
378 			 * softsign avoids negative 0 if _double < 0 but
379 			 * no significant digits will be shown.
380 			 */
381 			cp = buf;
382 			*cp = '\0';
383 			size = cvt(_double, prec, flags, &softsign, ch,
384 			    cp, buf + sizeof(buf));
385 			if (softsign)
386 				sign = '-';
387 			if (*cp == '\0')
388 				cp++;
389 			break;
390 #endif /* FLOATING_POINT */
391 		case 'n':
392 			if (flags & LONGINT)
393 				*va_arg(ap, long *) = ret;
394 			else if (flags & SHORTINT)
395 				*va_arg(ap, short *) = ret;
396 			else
397 				*va_arg(ap, int *) = ret;
398 			continue;	/* no output */
399 		case 'O':
400 			flags |= LONGINT;
401 			/*FALLTHROUGH*/
402 		case 'o':
403 			_ulong = UARG();
404 			base = OCT;
405 			goto nosign;
406 		case 'p':
407 			/*
408 			 * ``The argument shall be a pointer to void.  The
409 			 * value of the pointer is converted to a sequence
410 			 * of printable characters, in an implementation-
411 			 * defined manner.''
412 			 *	-- ANSI X3J11
413 			 */
414 			/* NOSTRICT */
415 			_ulong = (u_long)va_arg(ap, void *);
416 			base = HEX;
417 			xdigs = "0123456789abcdef";
418 			flags |= HEXPREFIX;
419 			ch = 'x';
420 			goto nosign;
421 		case 's':
422 			if ((cp = va_arg(ap, char *)) == NULL)
423 				cp = "(null)";
424 			if (prec >= 0) {
425 				/*
426 				 * can't use strlen; can only look for the
427 				 * NUL in the first `prec' characters, and
428 				 * strlen() will go further.
429 				 */
430 				char *p = memchr(cp, 0, prec);
431 
432 				if (p != NULL) {
433 					size = p - cp;
434 					if (size > prec)
435 						size = prec;
436 				} else
437 					size = prec;
438 			} else
439 				size = strlen(cp);
440 			sign = '\0';
441 			break;
442 		case 'U':
443 			flags |= LONGINT;
444 			/*FALLTHROUGH*/
445 		case 'u':
446 			_ulong = UARG();
447 			base = DEC;
448 			goto nosign;
449 		case 'X':
450 			xdigs = "0123456789ABCDEF";
451 			goto hex;
452 		case 'x':
453 			xdigs = "0123456789abcdef";
454 hex:			_ulong = UARG();
455 			base = HEX;
456 			/* leading 0x/X only if non-zero */
457 			if (flags & ALT && _ulong != 0)
458 				flags |= HEXPREFIX;
459 
460 			/* unsigned conversions */
461 nosign:			sign = '\0';
462 			/*
463 			 * ``... diouXx conversions ... if a precision is
464 			 * specified, the 0 flag will be ignored.''
465 			 *	-- ANSI X3J11
466 			 */
467 number:			if ((dprec = prec) >= 0)
468 				flags &= ~ZEROPAD;
469 
470 			/*
471 			 * ``The result of converting a zero value with an
472 			 * explicit precision of zero is no characters.''
473 			 *	-- ANSI X3J11
474 			 */
475 			cp = buf + BUF;
476 			if (_ulong != 0 || prec != 0) {
477 				/*
478 				 * unsigned mod is hard, and unsigned mod
479 				 * by a constant is easier than that by
480 				 * a variable; hence this switch.
481 				 */
482 				switch (base) {
483 				case OCT:
484 					do {
485 						*--cp = to_char(_ulong & 7);
486 						_ulong >>= 3;
487 					} while (_ulong);
488 					/* handle octal leading 0 */
489 					if (flags & ALT && *cp != '0')
490 						*--cp = '0';
491 					break;
492 
493 				case DEC:
494 					/* many numbers are 1 digit */
495 					while (_ulong >= 10) {
496 						*--cp = to_char(_ulong % 10);
497 						_ulong /= 10;
498 					}
499 					*--cp = to_char(_ulong);
500 					break;
501 
502 				case HEX:
503 					do {
504 						*--cp = xdigs[_ulong & 15];
505 						_ulong >>= 4;
506 					} while (_ulong);
507 					break;
508 
509 				default:
510 					cp = "bug in vfprintf: bad base";
511 					size = strlen(cp);
512 					goto skipsize;
513 				}
514 			}
515 			size = buf + BUF - cp;
516 		skipsize:
517 			break;
518 		default:	/* "%?" prints ?, unless ? is NUL */
519 			if (ch == '\0')
520 				goto done;
521 			/* pretend it was %c with argument ch */
522 			cp = buf;
523 			*cp = ch;
524 			size = 1;
525 			sign = '\0';
526 			break;
527 		}
528 
529 		/*
530 		 * All reasonable formats wind up here.  At this point,
531 		 * `cp' points to a string which (if not flags&LADJUST)
532 		 * should be padded out to `width' places.  If
533 		 * flags&ZEROPAD, it should first be prefixed by any
534 		 * sign or other prefix; otherwise, it should be blank
535 		 * padded before the prefix is emitted.  After any
536 		 * left-hand padding and prefixing, emit zeroes
537 		 * required by a decimal [diouxX] precision, then print
538 		 * the string proper, then emit zeroes required by any
539 		 * leftover floating precision; finally, if LADJUST,
540 		 * pad with blanks.
541 		 */
542 
543 		/*
544 		 * compute actual size, so we know how much to pad.
545 		 * fieldsz excludes decimal prec; realsz includes it
546 		 */
547 #ifdef FLOATING_POINT
548 		fieldsz = size + fpprec;
549 #else
550 		fieldsz = size;
551 #endif
552 		if (sign)
553 			fieldsz++;
554 		else if (flags & HEXPREFIX)
555 			fieldsz += 2;
556 		realsz = dprec > fieldsz ? dprec : fieldsz;
557 
558 		/* right-adjusting blank padding */
559 		if ((flags & (LADJUST|ZEROPAD)) == 0)
560 			PAD(width - realsz, blanks);
561 
562 		/* prefix */
563 		if (sign) {
564 			PRINT(&sign, 1);
565 		} else if (flags & HEXPREFIX) {
566 			ox[0] = '0';
567 			ox[1] = ch;
568 			PRINT(ox, 2);
569 		}
570 
571 		/* right-adjusting zero padding */
572 		if ((flags & (LADJUST|ZEROPAD)) == ZEROPAD)
573 			PAD(width - realsz, zeroes);
574 
575 		/* leading zeroes from decimal precision */
576 		PAD(dprec - fieldsz, zeroes);
577 
578 		/* the string or number proper */
579 		PRINT(cp, size);
580 
581 #ifdef FLOATING_POINT
582 		/* trailing f.p. zeroes */
583 		PAD(fpprec, zeroes);
584 #endif
585 
586 		/* left-adjusting padding (always blank) */
587 		if (flags & LADJUST)
588 			PAD(width - realsz, blanks);
589 
590 		/* finally, adjust ret */
591 		ret += width > realsz ? width : realsz;
592 
593 		FLUSH();	/* copy out the I/O vectors */
594 	}
595 done:
596 	FLUSH();
597 error:
598 	return (__sferror(fp) ? EOF : ret);
599 	/* NOTREACHED */
600 }
601 
602 #ifdef FLOATING_POINT
603 #include <math.h>
604 
605 static char *exponent();
606 static char *round();
607 
608 static int
609 cvt(number, prec, flags, signp, fmtch, startp, endp)
610 	double number;
611 	register int prec;
612 	int flags;
613 	char *signp;
614 	int fmtch;
615 	char *startp, *endp;
616 {
617 	register char *p, *t;
618 	register double fract;
619 	int dotrim, expcnt, gformat;
620 	double integer, tmp;
621 
622 	dotrim = expcnt = gformat = 0;
623 	if (number < 0) {
624 		number = -number;
625 		*signp = '-';
626 	} else
627 		*signp = 0;
628 
629 	fract = modf(number, &integer);
630 
631 	/* get an extra slot for rounding. */
632 	t = ++startp;
633 
634 	/*
635 	 * get integer portion of number; put into the end of the buffer; the
636 	 * .01 is added for modf(356.0 / 10, &integer) returning .59999999...
637 	 */
638 	for (p = endp - 1; integer; ++expcnt) {
639 		tmp = modf(integer / 10, &integer);
640 		*p-- = to_char((int)((tmp + .01) * 10));
641 	}
642 	switch (fmtch) {
643 	case 'f':
644 		/* reverse integer into beginning of buffer */
645 		if (expcnt)
646 			for (; ++p < endp; *t++ = *p);
647 		else
648 			*t++ = '0';
649 		/*
650 		 * if precision required or alternate flag set, add in a
651 		 * decimal point.
652 		 */
653 		if (prec || flags&ALT)
654 			*t++ = '.';
655 		/* if requires more precision and some fraction left */
656 		if (fract) {
657 			if (prec)
658 				do {
659 					fract = modf(fract * 10, &tmp);
660 					*t++ = to_char((int)tmp);
661 				} while (--prec && fract);
662 			if (fract)
663 				startp = round(fract, (int *)NULL, startp,
664 				    t - 1, (char)0, signp);
665 		}
666 		for (; prec--; *t++ = '0');
667 		break;
668 	case 'e':
669 	case 'E':
670 eformat:	if (expcnt) {
671 			*t++ = *++p;
672 			if (prec || flags&ALT)
673 				*t++ = '.';
674 			/* if requires more precision and some integer left */
675 			for (; prec && ++p < endp; --prec)
676 				*t++ = *p;
677 			/*
678 			 * if done precision and more of the integer component,
679 			 * round using it; adjust fract so we don't re-round
680 			 * later.
681 			 */
682 			if (!prec && ++p < endp) {
683 				fract = 0;
684 				startp = round((double)0, &expcnt, startp,
685 				    t - 1, *p, signp);
686 			}
687 			/* adjust expcnt for digit in front of decimal */
688 			--expcnt;
689 		}
690 		/* until first fractional digit, decrement exponent */
691 		else if (fract) {
692 			/* adjust expcnt for digit in front of decimal */
693 			for (expcnt = -1;; --expcnt) {
694 				fract = modf(fract * 10, &tmp);
695 				if (tmp)
696 					break;
697 			}
698 			*t++ = to_char((int)tmp);
699 			if (prec || flags&ALT)
700 				*t++ = '.';
701 		}
702 		else {
703 			*t++ = '0';
704 			if (prec || flags&ALT)
705 				*t++ = '.';
706 		}
707 		/* if requires more precision and some fraction left */
708 		if (fract) {
709 			if (prec)
710 				do {
711 					fract = modf(fract * 10, &tmp);
712 					*t++ = to_char((int)tmp);
713 				} while (--prec && fract);
714 			if (fract)
715 				startp = round(fract, &expcnt, startp,
716 				    t - 1, (char)0, signp);
717 		}
718 		/* if requires more precision */
719 		for (; prec--; *t++ = '0');
720 
721 		/* unless alternate flag, trim any g/G format trailing 0's */
722 		if (gformat && !(flags&ALT)) {
723 			while (t > startp && *--t == '0');
724 			if (*t == '.')
725 				--t;
726 			++t;
727 		}
728 		t = exponent(t, expcnt, fmtch);
729 		break;
730 	case 'g':
731 	case 'G':
732 		/* a precision of 0 is treated as a precision of 1. */
733 		if (!prec)
734 			++prec;
735 		/*
736 		 * ``The style used depends on the value converted; style e
737 		 * will be used only if the exponent resulting from the
738 		 * conversion is less than -4 or greater than the precision.''
739 		 *	-- ANSI X3J11
740 		 */
741 		if (expcnt > prec || !expcnt && fract && fract < .0001) {
742 			/*
743 			 * g/G format counts "significant digits, not digits of
744 			 * precision; for the e/E format, this just causes an
745 			 * off-by-one problem, i.e. g/G considers the digit
746 			 * before the decimal point significant and e/E doesn't
747 			 * count it as precision.
748 			 */
749 			--prec;
750 			fmtch -= 2;		/* G->E, g->e */
751 			gformat = 1;
752 			goto eformat;
753 		}
754 		/*
755 		 * reverse integer into beginning of buffer,
756 		 * note, decrement precision
757 		 */
758 		if (expcnt)
759 			for (; ++p < endp; *t++ = *p, --prec);
760 		else
761 			*t++ = '0';
762 		/*
763 		 * if precision required or alternate flag set, add in a
764 		 * decimal point.  If no digits yet, add in leading 0.
765 		 */
766 		if (prec || flags&ALT) {
767 			dotrim = 1;
768 			*t++ = '.';
769 		}
770 		else
771 			dotrim = 0;
772 		/* if requires more precision and some fraction left */
773 		if (fract) {
774 			if (prec) {
775 				do {
776 					fract = modf(fract * 10, &tmp);
777 					*t++ = to_char((int)tmp);
778 				} while(!tmp);
779 				while (--prec && fract) {
780 					fract = modf(fract * 10, &tmp);
781 					*t++ = to_char((int)tmp);
782 				}
783 			}
784 			if (fract)
785 				startp = round(fract, (int *)NULL, startp,
786 				    t - 1, (char)0, signp);
787 		}
788 		/* alternate format, adds 0's for precision, else trim 0's */
789 		if (flags&ALT)
790 			for (; prec--; *t++ = '0');
791 		else if (dotrim) {
792 			while (t > startp && *--t == '0');
793 			if (*t != '.')
794 				++t;
795 		}
796 	}
797 	return (t - startp);
798 }
799 
800 static char *
801 round(fract, exp, start, end, ch, signp)
802 	double fract;
803 	int *exp;
804 	register char *start, *end;
805 	char ch, *signp;
806 {
807 	double tmp;
808 
809 	if (fract)
810 		(void)modf(fract * 10, &tmp);
811 	else
812 		tmp = to_digit(ch);
813 	if (tmp > 4)
814 		for (;; --end) {
815 			if (*end == '.')
816 				--end;
817 			if (++*end <= '9')
818 				break;
819 			*end = '0';
820 			if (end == start) {
821 				if (exp) {	/* e/E; increment exponent */
822 					*end = '1';
823 					++*exp;
824 				}
825 				else {		/* f; add extra digit */
826 				*--end = '1';
827 				--start;
828 				}
829 				break;
830 			}
831 		}
832 	/* ``"%.3f", (double)-0.0004'' gives you a negative 0. */
833 	else if (*signp == '-')
834 		for (;; --end) {
835 			if (*end == '.')
836 				--end;
837 			if (*end != '0')
838 				break;
839 			if (end == start)
840 				*signp = 0;
841 		}
842 	return (start);
843 }
844 
845 static char *
846 exponent(p, exp, fmtch)
847 	register char *p;
848 	register int exp;
849 	int fmtch;
850 {
851 	register char *t;
852 	char expbuf[MAXEXP];
853 
854 	*p++ = fmtch;
855 	if (exp < 0) {
856 		exp = -exp;
857 		*p++ = '-';
858 	}
859 	else
860 		*p++ = '+';
861 	t = expbuf + MAXEXP;
862 	if (exp > 9) {
863 		do {
864 			*--t = to_char(exp % 10);
865 		} while ((exp /= 10) > 9);
866 		*--t = to_char(exp);
867 		for (; t < expbuf + MAXEXP; *p++ = *t++);
868 	}
869 	else {
870 		*p++ = '0';
871 		*p++ = to_char(exp);
872 	}
873 	return (p);
874 }
875 #endif /* FLOATING_POINT */
876