Update.
[glibc.git] / stdio-common / printf_fp.c
blob33bc25bfd277e436b70562e9a0b45a55771512ef
1 /* Floating point output for `printf'.
2 Copyright (C) 1995, 1996, 1997 Free Software Foundation, Inc.
3 This file is part of the GNU C Library.
4 Written by Ulrich Drepper <drepper@gnu.ai.mit.edu>, 1995.
6 The GNU C Library is free software; you can redistribute it and/or
7 modify it under the terms of the GNU Library General Public License as
8 published by the Free Software Foundation; either version 2 of the
9 License, or (at your option) any later version.
11 The GNU C Library is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 Library General Public License for more details.
16 You should have received a copy of the GNU Library General Public
17 License along with the GNU C Library; see the file COPYING.LIB. If not,
18 write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
19 Boston, MA 02111-1307, USA. */
21 /* The gmp headers need some configuration frobs. */
22 #define HAVE_ALLOCA 1
24 #ifdef USE_IN_LIBIO
25 # include <libioP.h>
26 #else
27 # include <stdio.h>
28 #endif
29 #include <alloca.h>
30 #include <ctype.h>
31 #include <float.h>
32 #include <gmp-mparam.h>
33 #include <stdlib/gmp.h>
34 #include <stdlib/gmp-impl.h>
35 #include <stdlib/longlong.h>
36 #include <stdlib/fpioconst.h>
37 #include <locale/localeinfo.h>
38 #include <limits.h>
39 #include <math.h>
40 #include <printf.h>
41 #include <string.h>
42 #include <unistd.h>
43 #include <stdlib.h>
45 #define NDEBUG /* Undefine this for debugging assertions. */
46 #include <assert.h>
48 /* This defines make it possible to use the same code for GNU C library and
49 the GNU I/O library. */
50 #ifdef USE_IN_LIBIO
51 # define PUT(f, s, n) _IO_sputn (f, s, n)
52 # define PAD(f, c, n) _IO_padn (f, c, n)
53 /* We use this file GNU C library and GNU I/O library. So make
54 names equal. */
55 # undef putc
56 # define putc(c, f) _IO_putc_unlocked (c, f)
57 # define size_t _IO_size_t
58 # define FILE _IO_FILE
59 #else /* ! USE_IN_LIBIO */
60 # define PUT(f, s, n) fwrite (s, 1, n, f)
61 # define PAD(f, c, n) __printf_pad (f, c, n)
62 ssize_t __printf_pad __P ((FILE *, char pad, int n)); /* In vfprintf.c. */
63 #endif /* USE_IN_LIBIO */
65 /* Macros for doing the actual output. */
67 #define outchar(ch) \
68 do \
69 { \
70 register const int outc = (ch); \
71 if (putc (outc, fp) == EOF) \
72 return -1; \
73 ++done; \
74 } while (0)
76 #define PRINT(ptr, len) \
77 do \
78 { \
79 register size_t outlen = (len); \
80 if (len > 20) \
81 { \
82 if (PUT (fp, ptr, outlen) != outlen) \
83 return -1; \
84 ptr += outlen; \
85 done += outlen; \
86 } \
87 else \
88 { \
89 while (outlen-- > 0) \
90 outchar (*ptr++); \
91 } \
92 } while (0)
94 #define PADN(ch, len) \
95 do \
96 { \
97 if (PAD (fp, ch, len) != len) \
98 return -1; \
99 done += len; \
101 while (0)
103 /* We use the GNU MP library to handle large numbers.
105 An MP variable occupies a varying number of entries in its array. We keep
106 track of this number for efficiency reasons. Otherwise we would always
107 have to process the whole array. */
108 #define MPN_VAR(name) mp_limb_t *name; mp_size_t name##size
110 #define MPN_ASSIGN(dst,src) \
111 memcpy (dst, src, (dst##size = src##size) * sizeof (mp_limb_t))
112 #define MPN_GE(u,v) \
113 (u##size > v##size || (u##size == v##size && __mpn_cmp (u, v, u##size) >= 0))
115 extern int __isinfl (long double), __isnanl (long double);
117 extern mp_size_t __mpn_extract_double (mp_ptr res_ptr, mp_size_t size,
118 int *expt, int *is_neg,
119 double value);
120 extern mp_size_t __mpn_extract_long_double (mp_ptr res_ptr, mp_size_t size,
121 int *expt, int *is_neg,
122 long double value);
123 extern unsigned int __guess_grouping (unsigned int intdig_max,
124 const char *grouping, wchar_t sepchar);
127 static char *group_number (char *buf, char *bufend, unsigned int intdig_no,
128 const char *grouping, wchar_t thousands_sep)
129 internal_function;
133 __printf_fp (FILE *fp,
134 const struct printf_info *info,
135 const void *const *args)
137 /* The floating-point value to output. */
138 union
140 double dbl;
141 __long_double_t ldbl;
143 fpnum;
145 /* Locale-dependent representation of decimal point. */
146 wchar_t decimal;
148 /* Locale-dependent thousands separator and grouping specification. */
149 wchar_t thousands_sep;
150 const char *grouping;
152 /* "NaN" or "Inf" for the special cases. */
153 const char *special = NULL;
155 /* We need just a few limbs for the input before shifting to the right
156 position. */
157 mp_limb_t fp_input[(LDBL_MANT_DIG + BITS_PER_MP_LIMB - 1) / BITS_PER_MP_LIMB];
158 /* We need to shift the contents of fp_input by this amount of bits. */
159 int to_shift = 0;
161 /* The fraction of the floting-point value in question */
162 MPN_VAR(frac);
163 /* and the exponent. */
164 int exponent;
165 /* Sign of the exponent. */
166 int expsign = 0;
167 /* Sign of float number. */
168 int is_neg = 0;
170 /* Scaling factor. */
171 MPN_VAR(scale);
173 /* Temporary bignum value. */
174 MPN_VAR(tmp);
176 /* Digit which is result of last hack_digit() call. */
177 int digit;
179 /* The type of output format that will be used: 'e'/'E' or 'f'. */
180 int type;
182 /* Counter for number of written characters. */
183 int done = 0;
185 /* General helper (carry limb). */
186 mp_limb_t cy;
188 char hack_digit (void)
190 mp_limb_t hi;
192 if (expsign != 0 && type == 'f' && exponent-- > 0)
193 hi = 0;
194 else if (scalesize == 0)
196 hi = frac[fracsize - 1];
197 cy = __mpn_mul_1 (frac, frac, fracsize - 1, 10);
198 frac[fracsize - 1] = cy;
200 else
202 if (fracsize < scalesize)
203 hi = 0;
204 else
206 hi = mpn_divmod (tmp, frac, fracsize, scale, scalesize);
207 tmp[fracsize - scalesize] = hi;
208 hi = tmp[0];
210 fracsize = scalesize;
211 while (fracsize != 0 && frac[fracsize - 1] == 0)
212 --fracsize;
213 if (fracsize == 0)
215 /* We're not prepared for an mpn variable with zero
216 limbs. */
217 fracsize = 1;
218 return '0' + hi;
222 cy = __mpn_mul_1 (frac, frac, fracsize, 10);
223 if (cy != 0)
224 frac[fracsize++] = cy;
227 return '0' + hi;
231 /* Figure out the decimal point character. */
232 if (info->extra == 0)
234 if (mbtowc (&decimal, _NL_CURRENT (LC_NUMERIC, DECIMAL_POINT),
235 strlen (_NL_CURRENT (LC_NUMERIC, DECIMAL_POINT))) <= 0)
236 decimal = (wchar_t) *_NL_CURRENT (LC_NUMERIC, DECIMAL_POINT);
238 else
240 if (mbtowc (&decimal, _NL_CURRENT (LC_MONETARY, MON_DECIMAL_POINT),
241 strlen (_NL_CURRENT (LC_MONETARY, MON_DECIMAL_POINT))) <= 0)
242 decimal = (wchar_t) *_NL_CURRENT (LC_MONETARY, MON_DECIMAL_POINT);
244 /* Give default value. */
245 if (decimal == L'\0')
246 decimal = L'.';
249 if (info->group)
251 if (info->extra == 0)
252 grouping = _NL_CURRENT (LC_NUMERIC, GROUPING);
253 else
254 grouping = _NL_CURRENT (LC_MONETARY, MON_GROUPING);
256 if (*grouping <= 0 || *grouping == CHAR_MAX)
257 grouping = NULL;
258 else
260 /* Figure out the thousands separator character. */
261 if (info->extra == 0)
263 if (mbtowc (&thousands_sep, _NL_CURRENT (LC_NUMERIC,
264 THOUSANDS_SEP),
265 strlen (_NL_CURRENT (LC_NUMERIC, THOUSANDS_SEP)))
266 <= 0)
267 thousands_sep = (wchar_t) *_NL_CURRENT (LC_NUMERIC,
268 THOUSANDS_SEP);
270 else
272 if (mbtowc (&thousands_sep, _NL_CURRENT (LC_MONETARY,
273 MON_THOUSANDS_SEP),
274 strlen (_NL_CURRENT (LC_MONETARY,
275 MON_THOUSANDS_SEP))) <= 0)
276 thousands_sep = (wchar_t) *_NL_CURRENT (LC_MONETARY,
277 MON_THOUSANDS_SEP);
280 if (thousands_sep == L'\0')
281 grouping = NULL;
284 else
285 grouping = NULL;
287 /* Fetch the argument value. */
288 if (info->is_long_double && sizeof (long double) > sizeof (double))
290 fpnum.ldbl = *(const long double *) args[0];
292 /* Check for special values: not a number or infinity. */
293 if (__isnanl (fpnum.ldbl))
295 special = isupper (info->spec) ? "NAN" : "nan";
296 is_neg = 0;
298 else if (__isinfl (fpnum.ldbl))
300 special = isupper (info->spec) ? "INF" : "inf";
301 is_neg = fpnum.ldbl < 0;
303 else
305 fracsize = __mpn_extract_long_double (fp_input,
306 (sizeof (fp_input) /
307 sizeof (fp_input[0])),
308 &exponent, &is_neg,
309 fpnum.ldbl);
310 to_shift = 1 + fracsize * BITS_PER_MP_LIMB - LDBL_MANT_DIG;
313 else
315 fpnum.dbl = *(const double *) args[0];
317 /* Check for special values: not a number or infinity. */
318 if (__isnan (fpnum.dbl))
320 special = isupper (info->spec) ? "NAN" : "nan";
321 is_neg = 0;
323 else if (__isinf (fpnum.dbl))
325 special = isupper (info->spec) ? "INF" : "inf";
326 is_neg = fpnum.dbl < 0;
328 else
330 fracsize = __mpn_extract_double (fp_input,
331 (sizeof (fp_input)
332 / sizeof (fp_input[0])),
333 &exponent, &is_neg, fpnum.dbl);
334 to_shift = 1 + fracsize * BITS_PER_MP_LIMB - DBL_MANT_DIG;
338 if (special)
340 int width = info->width;
342 if (is_neg || info->showsign || info->space)
343 --width;
344 width -= 3;
346 if (!info->left && width > 0)
347 PADN (' ', width);
349 if (is_neg)
350 outchar ('-');
351 else if (info->showsign)
352 outchar ('+');
353 else if (info->space)
354 outchar (' ');
356 PRINT (special, 3);
358 if (info->left && width > 0)
359 PADN (' ', width);
361 return done;
365 /* We need three multiprecision variables. Now that we have the exponent
366 of the number we can allocate the needed memory. It would be more
367 efficient to use variables of the fixed maximum size but because this
368 would be really big it could lead to memory problems. */
370 mp_size_t bignum_size = ((ABS (exponent) + BITS_PER_MP_LIMB - 1)
371 / BITS_PER_MP_LIMB + 4) * sizeof (mp_limb_t);
372 frac = (mp_limb_t *) alloca (bignum_size);
373 tmp = (mp_limb_t *) alloca (bignum_size);
374 scale = (mp_limb_t *) alloca (bignum_size);
377 /* We now have to distinguish between numbers with positive and negative
378 exponents because the method used for the one is not applicable/efficient
379 for the other. */
380 scalesize = 0;
381 if (exponent > 2)
383 /* |FP| >= 8.0. */
384 int scaleexpo = 0;
385 int explog = LDBL_MAX_10_EXP_LOG;
386 int exp10 = 0;
387 const struct mp_power *tens = &_fpioconst_pow10[explog + 1];
388 int cnt_h, cnt_l, i;
390 if ((exponent + to_shift) % BITS_PER_MP_LIMB == 0)
392 MPN_COPY_DECR (frac + (exponent + to_shift) / BITS_PER_MP_LIMB,
393 fp_input, fracsize);
394 fracsize += (exponent + to_shift) / BITS_PER_MP_LIMB;
396 else
398 cy = __mpn_lshift (frac + (exponent + to_shift) / BITS_PER_MP_LIMB,
399 fp_input, fracsize,
400 (exponent + to_shift) % BITS_PER_MP_LIMB);
401 fracsize += (exponent + to_shift) / BITS_PER_MP_LIMB;
402 if (cy)
403 frac[fracsize++] = cy;
405 MPN_ZERO (frac, (exponent + to_shift) / BITS_PER_MP_LIMB);
407 assert (tens > &_fpioconst_pow10[0]);
410 --tens;
412 /* The number of the product of two binary numbers with n and m
413 bits respectively has m+n or m+n-1 bits. */
414 if (exponent >= scaleexpo + tens->p_expo - 1)
416 if (scalesize == 0)
417 MPN_ASSIGN (tmp, tens->array);
418 else
420 cy = __mpn_mul (tmp, scale, scalesize,
421 &tens->array[_FPIO_CONST_OFFSET],
422 tens->arraysize - _FPIO_CONST_OFFSET);
423 tmpsize = scalesize + tens->arraysize - _FPIO_CONST_OFFSET;
424 if (cy == 0)
425 --tmpsize;
428 if (MPN_GE (frac, tmp))
430 int cnt;
431 MPN_ASSIGN (scale, tmp);
432 count_leading_zeros (cnt, scale[scalesize - 1]);
433 scaleexpo = (scalesize - 2) * BITS_PER_MP_LIMB - cnt - 1;
434 exp10 |= 1 << explog;
437 --explog;
439 while (tens > &_fpioconst_pow10[0]);
440 exponent = exp10;
442 /* Optimize number representations. We want to represent the numbers
443 with the lowest number of bytes possible without losing any
444 bytes. Also the highest bit in the scaling factor has to be set
445 (this is a requirement of the MPN division routines). */
446 if (scalesize > 0)
448 /* Determine minimum number of zero bits at the end of
449 both numbers. */
450 for (i = 0; scale[i] == 0 && frac[i] == 0; i++)
453 /* Determine number of bits the scaling factor is misplaced. */
454 count_leading_zeros (cnt_h, scale[scalesize - 1]);
456 if (cnt_h == 0)
458 /* The highest bit of the scaling factor is already set. So
459 we only have to remove the trailing empty limbs. */
460 if (i > 0)
462 MPN_COPY_INCR (scale, scale + i, scalesize - i);
463 scalesize -= i;
464 MPN_COPY_INCR (frac, frac + i, fracsize - i);
465 fracsize -= i;
468 else
470 if (scale[i] != 0)
472 count_trailing_zeros (cnt_l, scale[i]);
473 if (frac[i] != 0)
475 int cnt_l2;
476 count_trailing_zeros (cnt_l2, frac[i]);
477 if (cnt_l2 < cnt_l)
478 cnt_l = cnt_l2;
481 else
482 count_trailing_zeros (cnt_l, frac[i]);
484 /* Now shift the numbers to their optimal position. */
485 if (i == 0 && BITS_PER_MP_LIMB - cnt_h > cnt_l)
487 /* We cannot save any memory. So just roll both numbers
488 so that the scaling factor has its highest bit set. */
490 (void) __mpn_lshift (scale, scale, scalesize, cnt_h);
491 cy = __mpn_lshift (frac, frac, fracsize, cnt_h);
492 if (cy != 0)
493 frac[fracsize++] = cy;
495 else if (BITS_PER_MP_LIMB - cnt_h <= cnt_l)
497 /* We can save memory by removing the trailing zero limbs
498 and by packing the non-zero limbs which gain another
499 free one. */
501 (void) __mpn_rshift (scale, scale + i, scalesize - i,
502 BITS_PER_MP_LIMB - cnt_h);
503 scalesize -= i + 1;
504 (void) __mpn_rshift (frac, frac + i, fracsize - i,
505 BITS_PER_MP_LIMB - cnt_h);
506 fracsize -= frac[fracsize - i - 1] == 0 ? i + 1 : i;
508 else
510 /* We can only save the memory of the limbs which are zero.
511 The non-zero parts occupy the same number of limbs. */
513 (void) __mpn_rshift (scale, scale + (i - 1),
514 scalesize - (i - 1),
515 BITS_PER_MP_LIMB - cnt_h);
516 scalesize -= i;
517 (void) __mpn_rshift (frac, frac + (i - 1),
518 fracsize - (i - 1),
519 BITS_PER_MP_LIMB - cnt_h);
520 fracsize -= frac[fracsize - (i - 1) - 1] == 0 ? i : i - 1;
525 else if (exponent < 0)
527 /* |FP| < 1.0. */
528 int exp10 = 0;
529 int explog = LDBL_MAX_10_EXP_LOG;
530 const struct mp_power *tens = &_fpioconst_pow10[explog + 1];
531 mp_size_t used_limbs = fracsize - 1;
533 /* Now shift the input value to its right place. */
534 cy = __mpn_lshift (frac, fp_input, fracsize, to_shift);
535 frac[fracsize++] = cy;
536 assert (cy == 1 || (frac[fracsize - 2] == 0 && frac[0] == 0));
538 expsign = 1;
539 exponent = -exponent;
541 assert (tens != &_fpioconst_pow10[0]);
544 --tens;
546 if (exponent >= tens->m_expo)
548 int i, incr, cnt_h, cnt_l;
549 mp_limb_t topval[2];
551 /* The __mpn_mul function expects the first argument to be
552 bigger than the second. */
553 if (fracsize < tens->arraysize - _FPIO_CONST_OFFSET)
554 cy = __mpn_mul (tmp, &tens->array[_FPIO_CONST_OFFSET],
555 tens->arraysize - _FPIO_CONST_OFFSET,
556 frac, fracsize);
557 else
558 cy = __mpn_mul (tmp, frac, fracsize,
559 &tens->array[_FPIO_CONST_OFFSET],
560 tens->arraysize - _FPIO_CONST_OFFSET);
561 tmpsize = fracsize + tens->arraysize - _FPIO_CONST_OFFSET;
562 if (cy == 0)
563 --tmpsize;
565 count_leading_zeros (cnt_h, tmp[tmpsize - 1]);
566 incr = (tmpsize - fracsize) * BITS_PER_MP_LIMB
567 + BITS_PER_MP_LIMB - 1 - cnt_h;
569 assert (incr <= tens->p_expo);
571 /* If we increased the exponent by exactly 3 we have to test
572 for overflow. This is done by comparing with 10 shifted
573 to the right position. */
574 if (incr == exponent + 3)
575 if (cnt_h <= BITS_PER_MP_LIMB - 4)
577 topval[0] = 0;
578 topval[1]
579 = ((mp_limb_t) 10) << (BITS_PER_MP_LIMB - 4 - cnt_h);
581 else
583 topval[0] = ((mp_limb_t) 10) << (BITS_PER_MP_LIMB - 4);
584 topval[1] = 0;
585 (void) __mpn_lshift (topval, topval, 2,
586 BITS_PER_MP_LIMB - cnt_h);
589 /* We have to be careful when multiplying the last factor.
590 If the result is greater than 1.0 be have to test it
591 against 10.0. If it is greater or equal to 10.0 the
592 multiplication was not valid. This is because we cannot
593 determine the number of bits in the result in advance. */
594 if (incr < exponent + 3
595 || (incr == exponent + 3 &&
596 (tmp[tmpsize - 1] < topval[1]
597 || (tmp[tmpsize - 1] == topval[1]
598 && tmp[tmpsize - 2] < topval[0]))))
600 /* The factor is right. Adapt binary and decimal
601 exponents. */
602 exponent -= incr;
603 exp10 |= 1 << explog;
605 /* If this factor yields a number greater or equal to
606 1.0, we must not shift the non-fractional digits down. */
607 if (exponent < 0)
608 cnt_h += -exponent;
610 /* Now we optimize the number representation. */
611 for (i = 0; tmp[i] == 0; ++i);
612 if (cnt_h == BITS_PER_MP_LIMB - 1)
614 MPN_COPY (frac, tmp + i, tmpsize - i);
615 fracsize = tmpsize - i;
617 else
619 count_trailing_zeros (cnt_l, tmp[i]);
621 /* Now shift the numbers to their optimal position. */
622 if (i == 0 && BITS_PER_MP_LIMB - 1 - cnt_h > cnt_l)
624 /* We cannot save any memory. Just roll the
625 number so that the leading digit is in a
626 separate limb. */
628 cy = __mpn_lshift (frac, tmp, tmpsize, cnt_h + 1);
629 fracsize = tmpsize + 1;
630 frac[fracsize - 1] = cy;
632 else if (BITS_PER_MP_LIMB - 1 - cnt_h <= cnt_l)
634 (void) __mpn_rshift (frac, tmp + i, tmpsize - i,
635 BITS_PER_MP_LIMB - 1 - cnt_h);
636 fracsize = tmpsize - i;
638 else
640 /* We can only save the memory of the limbs which
641 are zero. The non-zero parts occupy the same
642 number of limbs. */
644 (void) __mpn_rshift (frac, tmp + (i - 1),
645 tmpsize - (i - 1),
646 BITS_PER_MP_LIMB - 1 - cnt_h);
647 fracsize = tmpsize - (i - 1);
650 used_limbs = fracsize - 1;
653 --explog;
655 while (tens != &_fpioconst_pow10[1] && exponent > 0);
656 /* All factors but 10^-1 are tested now. */
657 if (exponent > 0)
659 int cnt_l;
661 cy = __mpn_mul_1 (tmp, frac, fracsize, 10);
662 tmpsize = fracsize;
663 assert (cy == 0 || tmp[tmpsize - 1] < 20);
665 count_trailing_zeros (cnt_l, tmp[0]);
666 if (cnt_l < MIN (4, exponent))
668 cy = __mpn_lshift (frac, tmp, tmpsize,
669 BITS_PER_MP_LIMB - MIN (4, exponent));
670 if (cy != 0)
671 frac[tmpsize++] = cy;
673 else
674 (void) __mpn_rshift (frac, tmp, tmpsize, MIN (4, exponent));
675 fracsize = tmpsize;
676 exp10 |= 1;
677 assert (frac[fracsize - 1] < 10);
679 exponent = exp10;
681 else
683 /* This is a special case. We don't need a factor because the
684 numbers are in the range of 0.0 <= fp < 8.0. We simply
685 shift it to the right place and divide it by 1.0 to get the
686 leading digit. (Of course this division is not really made.) */
687 assert (0 <= exponent && exponent < 3 &&
688 exponent + to_shift < BITS_PER_MP_LIMB);
690 /* Now shift the input value to its right place. */
691 cy = __mpn_lshift (frac, fp_input, fracsize, (exponent + to_shift));
692 frac[fracsize++] = cy;
693 exponent = 0;
697 int width = info->width;
698 char *buffer, *startp, *cp;
699 int chars_needed;
700 int expscale;
701 int intdig_max, intdig_no = 0;
702 int fracdig_min, fracdig_max, fracdig_no = 0;
703 int dig_max;
704 int significant;
706 if (tolower (info->spec) == 'e')
708 type = info->spec;
709 intdig_max = 1;
710 fracdig_min = fracdig_max = info->prec < 0 ? 6 : info->prec;
711 chars_needed = 1 + 1 + fracdig_max + 1 + 1 + 4;
712 /* d . ddd e +- ddd */
713 dig_max = INT_MAX; /* Unlimited. */
714 significant = 1; /* Does not matter here. */
716 else if (info->spec == 'f')
718 type = 'f';
719 fracdig_min = fracdig_max = info->prec < 0 ? 6 : info->prec;
720 if (expsign == 0)
722 intdig_max = exponent + 1;
723 /* This can be really big! */ /* XXX Maybe malloc if too big? */
724 chars_needed = exponent + 1 + 1 + fracdig_max;
726 else
728 intdig_max = 1;
729 chars_needed = 1 + 1 + fracdig_max;
731 dig_max = INT_MAX; /* Unlimited. */
732 significant = 1; /* Does not matter here. */
734 else
736 dig_max = info->prec < 0 ? 6 : (info->prec == 0 ? 1 : info->prec);
737 if ((expsign == 0 && exponent >= dig_max)
738 || (expsign != 0 && exponent > 4))
740 type = isupper (info->spec) ? 'E' : 'e';
741 fracdig_max = dig_max - 1;
742 intdig_max = 1;
743 chars_needed = 1 + 1 + fracdig_max + 1 + 1 + 4;
745 else
747 type = 'f';
748 intdig_max = expsign == 0 ? exponent + 1 : 0;
749 fracdig_max = dig_max - intdig_max;
750 /* We need space for the significant digits and perhaps for
751 leading zeros when < 1.0. Pessimistic guess: dig_max. */
752 chars_needed = dig_max + dig_max + 1;
754 fracdig_min = info->alt ? fracdig_max : 0;
755 significant = 0; /* We count significant digits. */
758 if (grouping)
759 /* Guess the number of groups we will make, and thus how
760 many spaces we need for separator characters. */
761 chars_needed += __guess_grouping (intdig_max, grouping, thousands_sep);
763 /* Allocate buffer for output. We need two more because while rounding
764 it is possible that we need two more characters in front of all the
765 other output. */
766 buffer = alloca (2 + chars_needed);
767 cp = startp = buffer + 2; /* Let room for rounding. */
769 /* Do the real work: put digits in allocated buffer. */
770 if (expsign == 0 || type != 'f')
772 assert (expsign == 0 || intdig_max == 1);
773 while (intdig_no < intdig_max)
775 ++intdig_no;
776 *cp++ = hack_digit ();
778 significant = 1;
779 if (info->alt
780 || fracdig_min > 0
781 || (fracdig_max > 0 && (fracsize > 1 || frac[0] != 0)))
782 *cp++ = decimal;
784 else
786 /* |fp| < 1.0 and the selected type is 'f', so put "0."
787 in the buffer. */
788 *cp++ = '0';
789 --exponent;
790 *cp++ = decimal;
793 /* Generate the needed number of fractional digits. */
794 while (fracdig_no < fracdig_min
795 || (fracdig_no < fracdig_max && (fracsize > 1 || frac[0] != 0)))
797 ++fracdig_no;
798 *cp = hack_digit ();
799 if (*cp != '0')
800 significant = 1;
801 else if (significant == 0)
803 ++fracdig_max;
804 if (fracdig_min > 0)
805 ++fracdig_min;
807 ++cp;
810 /* Do rounding. */
811 digit = hack_digit ();
812 if (digit > '4')
814 char *tp = cp;
816 if (digit == '5' && (*(cp - 1) & 1) == 0)
817 /* This is the critical case. */
818 if (fracsize == 1 && frac[0] == 0)
819 /* Rest of the number is zero -> round to even.
820 (IEEE 754-1985 4.1 says this is the default rounding.) */
821 goto do_expo;
822 else if (scalesize == 0)
824 /* Here we have to see whether all limbs are zero since no
825 normalization happened. */
826 size_t lcnt = fracsize;
827 while (lcnt >= 1 && frac[lcnt - 1] == 0)
828 --lcnt;
829 if (lcnt == 0)
830 /* Rest of the number is zero -> round to even.
831 (IEEE 754-1985 4.1 says this is the default rounding.) */
832 goto do_expo;
835 if (fracdig_no > 0)
837 /* Process fractional digits. Terminate if not rounded or
838 radix character is reached. */
839 while (*--tp != decimal && *tp == '9')
840 *tp = '0';
841 if (*tp != decimal)
842 /* Round up. */
843 (*tp)++;
846 if (fracdig_no == 0 || *tp == decimal)
848 /* Round the integer digits. */
849 if (*(tp - 1) == decimal)
850 --tp;
852 while (--tp >= startp && *tp == '9')
853 *tp = '0';
855 if (tp >= startp)
856 /* Round up. */
857 (*tp)++;
858 else
859 /* It is more critical. All digits were 9's. */
861 if (type != 'f')
863 *startp = '1';
864 exponent += expsign == 0 ? 1 : -1;
866 else if (intdig_no == dig_max)
868 /* This is the case where for type %g the number fits
869 really in the range for %f output but after rounding
870 the number of digits is too big. */
871 *--startp = decimal;
872 *--startp = '1';
874 if (info->alt || fracdig_no > 0)
876 /* Overwrite the old radix character. */
877 startp[intdig_no + 2] = '0';
878 ++fracdig_no;
881 fracdig_no += intdig_no;
882 intdig_no = 1;
883 fracdig_max = intdig_max - intdig_no;
884 ++exponent;
885 /* Now we must print the exponent. */
886 type = isupper (info->spec) ? 'E' : 'e';
888 else
890 /* We can simply add another another digit before the
891 radix. */
892 *--startp = '1';
893 ++intdig_no;
896 /* While rounding the number of digits can change.
897 If the number now exceeds the limits remove some
898 fractional digits. */
899 if (intdig_no + fracdig_no > dig_max)
901 cp -= intdig_no + fracdig_no - dig_max;
902 fracdig_no -= intdig_no + fracdig_no - dig_max;
908 do_expo:
909 /* Now remove unnecessary '0' at the end of the string. */
910 while (fracdig_no > fracdig_min && *(cp - 1) == '0')
912 --cp;
913 --fracdig_no;
915 /* If we eliminate all fractional digits we perhaps also can remove
916 the radix character. */
917 if (fracdig_no == 0 && !info->alt && *(cp - 1) == decimal)
918 --cp;
920 if (grouping)
921 /* Add in separator characters, overwriting the same buffer. */
922 cp = group_number (startp, cp, intdig_no, grouping, thousands_sep);
924 /* Write the exponent if it is needed. */
925 if (type != 'f')
927 *cp++ = type;
928 *cp++ = expsign ? '-' : '+';
930 /* Find the magnitude of the exponent. */
931 expscale = 10;
932 while (expscale <= exponent)
933 expscale *= 10;
935 if (exponent < 10)
936 /* Exponent always has at least two digits. */
937 *cp++ = '0';
938 else
941 expscale /= 10;
942 *cp++ = '0' + (exponent / expscale);
943 exponent %= expscale;
945 while (expscale > 10);
946 *cp++ = '0' + exponent;
949 /* Compute number of characters which must be filled with the padding
950 character. */
951 if (is_neg || info->showsign || info->space)
952 --width;
953 width -= cp - startp;
955 if (!info->left && info->pad != '0' && width > 0)
956 PADN (info->pad, width);
958 if (is_neg)
959 outchar ('-');
960 else if (info->showsign)
961 outchar ('+');
962 else if (info->space)
963 outchar (' ');
965 if (!info->left && info->pad == '0' && width > 0)
966 PADN ('0', width);
968 PRINT (startp, cp - startp);
970 if (info->left && width > 0)
971 PADN (info->pad, width);
973 return done;
976 /* Return the number of extra grouping characters that will be inserted
977 into a number with INTDIG_MAX integer digits. */
979 unsigned int
980 __guess_grouping (unsigned int intdig_max, const char *grouping,
981 wchar_t sepchar)
983 unsigned int groups;
985 /* We treat all negative values like CHAR_MAX. */
987 if (*grouping == CHAR_MAX || *grouping <= 0)
988 /* No grouping should be done. */
989 return 0;
991 groups = 0;
992 while (intdig_max > (unsigned int) *grouping)
994 ++groups;
995 intdig_max -= *grouping++;
997 if (*grouping == CHAR_MAX
998 #if CHAR_MIN < 0
999 || *grouping < 0
1000 #endif
1002 /* No more grouping should be done. */
1003 break;
1004 else if (*grouping == 0)
1006 /* Same grouping repeats. */
1007 groups += (intdig_max - 1) / grouping[-1];
1008 break;
1012 return groups;
1015 /* Group the INTDIG_NO integer digits of the number in [BUF,BUFEND).
1016 There is guaranteed enough space past BUFEND to extend it.
1017 Return the new end of buffer. */
1019 static char *
1020 internal_function
1021 group_number (char *buf, char *bufend, unsigned int intdig_no,
1022 const char *grouping, wchar_t thousands_sep)
1024 unsigned int groups = __guess_grouping (intdig_no, grouping, thousands_sep);
1025 char *p;
1027 if (groups == 0)
1028 return bufend;
1030 /* Move the fractional part down. */
1031 memmove (buf + intdig_no + groups, buf + intdig_no,
1032 bufend - (buf + intdig_no));
1034 p = buf + intdig_no + groups - 1;
1037 unsigned int len = *grouping++;
1039 *p-- = buf[--intdig_no];
1040 while (--len > 0);
1041 *p-- = thousands_sep;
1043 if (*grouping == CHAR_MAX
1044 #if CHAR_MIN < 0
1045 || *grouping < 0
1046 #endif
1048 /* No more grouping should be done. */
1049 break;
1050 else if (*grouping == 0)
1051 /* Same grouping repeats. */
1052 --grouping;
1053 } while (intdig_no > (unsigned int) *grouping);
1055 /* Copy the remaining ungrouped digits. */
1057 *p-- = buf[--intdig_no];
1058 while (p > buf);
1060 return bufend + groups;