* malloc/mcheck.c (mabort): Declare prototype.
[glibc.git] / stdio-common / printf_fp.c
blob747491f012067d7e8dc2e5ba2fc6c7ec54db5be0
1 /* Floating point output for `printf'.
2 Copyright (C) 1995, 1996 Free Software Foundation, Inc.
3 Written by Ulrich Drepper.
5 This file is part of the GNU C Library.
7 The GNU C Library is free software; you can redistribute it and/or
8 modify it under the terms of the GNU Library General Public License as
9 published by the Free Software Foundation; either version 2 of the
10 License, or (at your option) any later version.
12 The GNU C Library is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 Library General Public License for more details.
17 You should have received a copy of the GNU Library General Public
18 License along with the GNU C Library; see the file COPYING.LIB. If
19 not, write to the Free Software Foundation, Inc., 675 Mass Ave,
20 Cambridge, MA 02139, USA. */
22 #ifdef USE_IN_LIBIO
23 # include <libioP.h>
24 #else
25 # include <stdio.h>
26 #endif
27 #include <alloca.h>
28 #include <ansidecl.h>
29 #include <ctype.h>
30 #include <float.h>
31 #include <gmp-mparam.h>
32 #include "../stdlib/gmp.h"
33 #include "../stdlib/gmp-impl.h"
34 #include "../stdlib/longlong.h"
35 #include "../stdlib/fpioconst.h"
36 #include "../locale/localeinfo.h"
37 #include <limits.h>
38 #include <math.h>
39 #include <printf.h>
40 #include <string.h>
41 #include <unistd.h>
42 #include <stdlib.h>
44 #define NDEBUG /* Undefine this for debugging assertions. */
45 #include <assert.h>
47 /* This defines make it possible to use the same code for GNU C library and
48 the GNU I/O library. */
49 #ifdef USE_IN_LIBIO
50 # define PUT(f, s, n) _IO_sputn (f, s, n)
51 # define PAD(f, c, n) _IO_padn (f, c, n)
52 /* We use this file GNU C library and GNU I/O library. So make
53 names equal. */
54 # undef putc
55 # define putc(c, f) _IO_putc (c, f)
56 # define size_t _IO_size_t
57 # define FILE _IO_FILE
58 #else /* ! USE_IN_LIBIO */
59 # define PUT(f, s, n) fwrite (s, 1, n, f)
60 # define PAD(f, c, n) __printf_pad (f, c, n)
61 ssize_t __printf_pad __P ((FILE *, char pad, int n)); /* In vfprintf.c. */
62 #endif /* USE_IN_LIBIO */
64 /* Macros for doing the actual output. */
66 #define outchar(ch) \
67 do \
68 { \
69 register CONST int outc = (ch); \
70 if (putc (outc, fp) == EOF) \
71 return -1; \
72 ++done; \
73 } while (0)
75 #define PRINT(ptr, len) \
76 do \
77 { \
78 register size_t outlen = (len); \
79 if (len > 20) \
80 { \
81 if (PUT (fp, ptr, outlen) != outlen) \
82 return -1; \
83 ptr += outlen; \
84 done += outlen; \
85 } \
86 else \
87 { \
88 while (outlen-- > 0) \
89 outchar (*ptr++); \
90 } \
91 } while (0)
93 #define PADN(ch, len) \
94 do \
95 { \
96 if (PAD (fp, ch, len) != len) \
97 return -1; \
98 done += len; \
99 } \
100 while (0)
102 /* We use the GNU MP library to handle large numbers.
104 An MP variable occupies a varying number of entries in its array. We keep
105 track of this number for efficiency reasons. Otherwise we would always
106 have to process the whole array. */
107 #define MPN_VAR(name) mp_limb *name; mp_size_t name##size
109 #define MPN_ASSIGN(dst,src) \
110 memcpy (dst, src, (dst##size = src##size) * sizeof (mp_limb))
111 #define MPN_GE(u,v) \
112 (u##size > v##size || (u##size == v##size && __mpn_cmp (u, v, u##size) >= 0))
114 extern int __isinfl (long double), __isnanl (long double);
116 extern mp_size_t __mpn_extract_double (mp_ptr res_ptr, mp_size_t size,
117 int *expt, int *is_neg,
118 double value);
119 extern mp_size_t __mpn_extract_long_double (mp_ptr res_ptr, mp_size_t size,
120 int *expt, int *is_neg,
121 long double value);
124 static unsigned int guess_grouping (unsigned int intdig_max,
125 const char *grouping, wchar_t sepchar);
126 static char *group_number (char *buf, char *bufend, unsigned int intdig_no,
127 const char *grouping, wchar_t thousands_sep);
131 __printf_fp (FILE *fp,
132 const struct printf_info *info,
133 const *const *args)
135 /* The floating-point value to output. */
136 union
138 double dbl;
139 LONG_DOUBLE ldbl;
141 fpnum;
143 /* Locale-dependent representation of decimal point. */
144 wchar_t decimal;
146 /* Locale-dependent thousands separator and grouping specification. */
147 wchar_t thousands_sep;
148 const char *grouping;
150 /* "NaN" or "Inf" for the special cases. */
151 CONST char *special = NULL;
153 /* We need just a few limbs for the input before shifting to the right
154 position. */
155 mp_limb fp_input[(LDBL_MANT_DIG + BITS_PER_MP_LIMB - 1) / BITS_PER_MP_LIMB];
156 /* We need to shift the contents of fp_input by this amount of bits. */
157 int to_shift;
159 /* The significant of the floting-point value in question */
160 MPN_VAR(frac);
161 /* and the exponent. */
162 int exponent;
163 /* Sign of the exponent. */
164 int expsign = 0;
165 /* Sign of float number. */
166 int is_neg = 0;
168 /* Scaling factor. */
169 MPN_VAR(scale);
171 /* Temporary bignum value. */
172 MPN_VAR(tmp);
174 /* Digit which is result of last hack_digit() call. */
175 int digit;
177 /* The type of output format that will be used: 'e'/'E' or 'f'. */
178 int type;
180 /* Counter for number of written characters. */
181 int done = 0;
183 /* General helper (carry limb). */
184 mp_limb cy;
186 char hack_digit (void)
188 mp_limb hi;
190 if (expsign != 0 && type == 'f' && exponent-- > 0)
191 hi = 0;
192 else if (scalesize == 0)
194 hi = frac[fracsize - 1];
195 cy = __mpn_mul_1 (frac, frac, fracsize - 1, 10);
196 frac[fracsize - 1] = cy;
198 else
200 if (fracsize < scalesize)
201 hi = 0;
202 else
204 hi = __mpn_divmod (tmp, frac, fracsize, scale, scalesize);
205 tmp[fracsize - scalesize] = hi;
206 hi = tmp[0];
208 fracsize = __mpn_normal_size (frac, scalesize);
209 if (fracsize == 0)
211 /* We're not prepared for an mpn variable with zero
212 limbs. */
213 fracsize = 1;
214 return '0' + hi;
218 cy = __mpn_mul_1 (frac, frac, fracsize, 10);
219 if (cy != 0)
220 frac[fracsize++] = cy;
223 return '0' + hi;
227 /* Figure out the decimal point character. */
228 if (mbtowc (&decimal, _NL_CURRENT (LC_NUMERIC, DECIMAL_POINT),
229 strlen (_NL_CURRENT (LC_NUMERIC, DECIMAL_POINT))) <= 0)
230 decimal = (wchar_t) *_NL_CURRENT (LC_NUMERIC, DECIMAL_POINT);
233 if (info->group)
235 grouping = _NL_CURRENT (LC_NUMERIC, GROUPING);
236 if (*grouping <= 0 || *grouping == CHAR_MAX)
237 grouping = NULL;
238 else
240 /* Figure out the thousands seperator character. */
241 if (mbtowc (&thousands_sep, _NL_CURRENT (LC_NUMERIC, THOUSANDS_SEP),
242 strlen (_NL_CURRENT (LC_NUMERIC, THOUSANDS_SEP))) <= 0)
243 thousands_sep = (wchar_t) *_NL_CURRENT (LC_NUMERIC, THOUSANDS_SEP);
244 if (thousands_sep == L'\0')
245 grouping = NULL;
248 else
249 grouping = NULL;
251 /* Fetch the argument value. */
252 if (info->is_long_double && sizeof (long double) > sizeof (double))
254 fpnum.ldbl = *(const long double *) args[0];
256 /* Check for special values: not a number or infinity. */
257 if (__isnanl (fpnum.ldbl))
259 special = "NaN";
260 is_neg = 0;
262 else if (__isinfl (fpnum.ldbl))
264 special = "Inf";
265 is_neg = fpnum.ldbl < 0;
267 else
269 fracsize = __mpn_extract_long_double (fp_input,
270 (sizeof (fp_input) /
271 sizeof (fp_input[0])),
272 &exponent, &is_neg,
273 fpnum.ldbl);
274 to_shift = 1 + fracsize * BITS_PER_MP_LIMB - LDBL_MANT_DIG;
277 else
279 fpnum.dbl = *(const double *) args[0];
281 /* Check for special values: not a number or infinity. */
282 if (__isnan (fpnum.dbl))
284 special = "NaN";
285 is_neg = 0;
287 else if (__isinf (fpnum.dbl))
289 special = "Inf";
290 is_neg = fpnum.dbl < 0;
292 else
294 fracsize = __mpn_extract_double (fp_input,
295 (sizeof (fp_input)
296 / sizeof (fp_input[0])),
297 &exponent, &is_neg, fpnum.dbl);
298 to_shift = 1 + fracsize * BITS_PER_MP_LIMB - DBL_MANT_DIG;
302 if (special)
304 int width = info->prec > info->width ? info->prec : info->width;
306 if (is_neg || info->showsign || info->space)
307 --width;
308 width -= 3;
310 if (!info->left && width > 0)
311 PADN (' ', width);
313 if (is_neg)
314 outchar ('-');
315 else if (info->showsign)
316 outchar ('+');
317 else if (info->space)
318 outchar (' ');
320 PRINT (special, 3);
322 if (info->left && width > 0)
323 PADN (' ', width);
325 return done;
329 /* We need three multiprecision variables. Now that we have the exponent
330 of the number we can allocate the needed memory. It would be more
331 efficient to use variables of the fixed maximum size but because this
332 would be really big it could lead to memory problems. */
334 mp_size_t bignum_size = ((ABS (exponent) + BITS_PER_MP_LIMB - 1)
335 / BITS_PER_MP_LIMB + 3) * sizeof (mp_limb);
336 frac = (mp_limb *) alloca (bignum_size);
337 tmp = (mp_limb *) alloca (bignum_size);
338 scale = (mp_limb *) alloca (bignum_size);
341 /* We now have to distinguish between numbers with positive and negative
342 exponents because the method used for the one is not applicable/efficient
343 for the other. */
344 scalesize = 0;
345 if (exponent > 2)
347 /* |FP| >= 8.0. */
348 int scaleexpo = 0;
349 int explog = LDBL_MAX_10_EXP_LOG;
350 int exp10 = 0;
351 const struct mp_power *tens = &_fpioconst_pow10[explog + 1];
352 int cnt_h, cnt_l, i;
354 if ((exponent + to_shift) % BITS_PER_MP_LIMB == 0)
356 MPN_COPY_DECR (frac + (exponent + to_shift) / BITS_PER_MP_LIMB,
357 fp_input, fracsize);
358 fracsize += (exponent + to_shift) / BITS_PER_MP_LIMB;
360 else
362 cy = __mpn_lshift (frac + (exponent + to_shift) / BITS_PER_MP_LIMB,
363 fp_input, fracsize,
364 (exponent + to_shift) % BITS_PER_MP_LIMB);
365 fracsize += (exponent + to_shift) / BITS_PER_MP_LIMB;
366 if (cy)
367 frac[fracsize++] = cy;
369 MPN_ZERO (frac, (exponent + to_shift) / BITS_PER_MP_LIMB);
371 assert (tens > &_fpioconst_pow10[0]);
374 --tens;
376 /* The number of the product of two binary numbers with n and m
377 bits respectively has m+n or m+n-1 bits. */
378 if (exponent >= scaleexpo + tens->p_expo - 1)
380 if (scalesize == 0)
381 MPN_ASSIGN (tmp, tens->array);
382 else
384 cy = __mpn_mul (tmp, scale, scalesize,
385 tens->array + 2, tens->arraysize - 2);
386 tmpsize = scalesize + tens->arraysize - 2;
387 if (cy == 0)
388 --tmpsize;
391 if (MPN_GE (frac, tmp))
393 int cnt;
394 MPN_ASSIGN (scale, tmp);
395 count_leading_zeros (cnt, scale[scalesize - 1]);
396 scaleexpo = (scalesize - 2) * BITS_PER_MP_LIMB - cnt - 1;
397 exp10 |= 1 << explog;
400 --explog;
402 while (tens > &_fpioconst_pow10[0]);
403 exponent = exp10;
405 /* Optimize number representations. We want to represent the numbers
406 with the lowest number of bytes possible without losing any
407 bytes. Also the highest bit in the scaling factor has to be set
408 (this is a requirement of the MPN division routines). */
409 if (scalesize > 0)
411 /* Determine minimum number of zero bits at the end of
412 both numbers. */
413 for (i = 0; scale[i] == 0 && frac[i] == 0; i++)
416 /* Determine number of bits the scaling factor is misplaced. */
417 count_leading_zeros (cnt_h, scale[scalesize - 1]);
419 if (cnt_h == 0)
421 /* The highest bit of the scaling factor is already set. So
422 we only have to remove the trailing empty limbs. */
423 if (i > 0)
425 MPN_COPY_INCR (scale, scale + i, scalesize - i);
426 scalesize -= i;
427 MPN_COPY_INCR (frac, frac + i, fracsize - i);
428 fracsize -= i;
431 else
433 if (scale[i] != 0)
435 count_trailing_zeros (cnt_l, scale[i]);
436 if (frac[i] != 0)
438 int cnt_l2;
439 count_trailing_zeros (cnt_l2, frac[i]);
440 if (cnt_l2 < cnt_l)
441 cnt_l = cnt_l2;
444 else
445 count_trailing_zeros (cnt_l, frac[i]);
447 /* Now shift the numbers to their optimal position. */
448 if (i == 0 && BITS_PER_MP_LIMB - cnt_h > cnt_l)
450 /* We cannot save any memory. So just roll both numbers
451 so that the scaling factor has its highest bit set. */
453 (void) __mpn_lshift (scale, scale, scalesize, cnt_h);
454 cy = __mpn_lshift (frac, frac, fracsize, cnt_h);
455 if (cy != 0)
456 frac[fracsize++] = cy;
458 else if (BITS_PER_MP_LIMB - cnt_h <= cnt_l)
460 /* We can save memory by removing the trailing zero limbs
461 and by packing the non-zero limbs which gain another
462 free one. */
464 (void) __mpn_rshift (scale, scale + i, scalesize - i,
465 BITS_PER_MP_LIMB - cnt_h);
466 scalesize -= i + 1;
467 (void) __mpn_rshift (frac, frac + i, fracsize - i,
468 BITS_PER_MP_LIMB - cnt_h);
469 fracsize -= frac[fracsize - i - 1] == 0 ? i + 1 : i;
471 else
473 /* We can only save the memory of the limbs which are zero.
474 The non-zero parts occupy the same number of limbs. */
476 (void) __mpn_rshift (scale, scale + (i - 1),
477 scalesize - (i - 1),
478 BITS_PER_MP_LIMB - cnt_h);
479 scalesize -= i;
480 (void) __mpn_rshift (frac, frac + (i - 1),
481 fracsize - (i - 1),
482 BITS_PER_MP_LIMB - cnt_h);
483 fracsize -= frac[fracsize - (i - 1) - 1] == 0 ? i : i - 1;
488 else if (exponent < 0)
490 /* |FP| < 1.0. */
491 int exp10 = 0;
492 int explog = LDBL_MAX_10_EXP_LOG;
493 const struct mp_power *tens = &_fpioconst_pow10[explog + 1];
494 mp_size_t used_limbs = fracsize - 1;
496 /* Now shift the input value to its right place. */
497 cy = __mpn_lshift (frac, fp_input, fracsize, to_shift);
498 frac[fracsize++] = cy;
499 assert (cy == 1 || (frac[fracsize - 2] == 0 && frac[0] == 0));
501 expsign = 1;
502 exponent = -exponent;
504 assert (tens != &_fpioconst_pow10[0]);
507 --tens;
509 if (exponent >= tens->m_expo)
511 int i, incr, cnt_h, cnt_l;
512 mp_limb topval[2];
514 /* The __mpn_mul function expects the first argument to be
515 bigger than the second. */
516 if (fracsize < tens->arraysize - 2)
517 cy = __mpn_mul (tmp, &tens->array[2], tens->arraysize - 2,
518 frac, fracsize);
519 else
520 cy = __mpn_mul (tmp, frac, fracsize,
521 &tens->array[2], tens->arraysize - 2);
522 tmpsize = fracsize + tens->arraysize - 2;
523 if (cy == 0)
524 --tmpsize;
526 count_leading_zeros (cnt_h, tmp[tmpsize - 1]);
527 incr = (tmpsize - fracsize) * BITS_PER_MP_LIMB
528 + BITS_PER_MP_LIMB - 1 - cnt_h;
530 assert (incr <= tens->p_expo);
532 /* If we increased the exponent by exactly 3 we have to test
533 for overflow. This is done by comparing with 10 shifted
534 to the right position. */
535 if (incr == exponent + 3)
536 if (cnt_h <= BITS_PER_MP_LIMB - 4)
538 topval[0] = 0;
539 topval[1] = 10 << (BITS_PER_MP_LIMB - 4 - cnt_h);
541 else
543 topval[0] = 10 << (BITS_PER_MP_LIMB - 4);
544 topval[1] = 0;
545 (void) __mpn_lshift (topval, topval, 2,
546 BITS_PER_MP_LIMB - cnt_h);
549 /* We have to be careful when multiplying the last factor.
550 If the result is greater than 1.0 be have to test it
551 against 10.0. If it is greater or equal to 10.0 the
552 multiplication was not valid. This is because we cannot
553 determine the number of bits in the result in advance. */
554 if (incr < exponent + 3
555 || (incr == exponent + 3 &&
556 (tmp[tmpsize - 1] < topval[1]
557 || (tmp[tmpsize - 1] == topval[1]
558 && tmp[tmpsize - 2] < topval[0]))))
560 /* The factor is right. Adapt binary and decimal
561 exponents. */
562 exponent -= incr;
563 exp10 |= 1 << explog;
565 /* If this factor yields a number greater or equal to
566 1.0, we must not shift the non-fractional digits down. */
567 if (exponent < 0)
568 cnt_h += -exponent;
570 /* Now we optimize the number representation. */
571 for (i = 0; tmp[i] == 0; ++i);
572 if (cnt_h == BITS_PER_MP_LIMB - 1)
574 MPN_COPY (frac, tmp + i, tmpsize - i);
575 fracsize = tmpsize - i;
577 else
579 count_trailing_zeros (cnt_l, tmp[i]);
581 /* Now shift the numbers to their optimal position. */
582 if (i == 0 && BITS_PER_MP_LIMB - 1 - cnt_h > cnt_l)
584 /* We cannot save any memory. Just roll the
585 number so that the leading digit is in a
586 seperate limb. */
588 cy = __mpn_lshift (frac, tmp, tmpsize, cnt_h + 1);
589 fracsize = tmpsize + 1;
590 frac[fracsize - 1] = cy;
592 else if (BITS_PER_MP_LIMB - 1 - cnt_h <= cnt_l)
594 (void) __mpn_rshift (frac, tmp + i, tmpsize - i,
595 BITS_PER_MP_LIMB - 1 - cnt_h);
596 fracsize = tmpsize - i;
598 else
600 /* We can only save the memory of the limbs which
601 are zero. The non-zero parts occupy the same
602 number of limbs. */
604 (void) __mpn_rshift (frac, tmp + (i - 1),
605 tmpsize - (i - 1),
606 BITS_PER_MP_LIMB - 1 - cnt_h);
607 fracsize = tmpsize - (i - 1);
610 used_limbs = fracsize - 1;
613 --explog;
615 while (tens != &_fpioconst_pow10[1] && exponent > 0);
616 /* All factors but 10^-1 are tested now. */
617 if (exponent > 0)
619 cy = __mpn_mul_1 (tmp, frac, fracsize, 10);
620 tmpsize = fracsize;
621 assert (cy == 0 || tmp[tmpsize - 1] < 20);
623 (void) __mpn_rshift (frac, tmp, tmpsize, MIN (4, exponent));
624 fracsize = tmpsize;
625 exp10 |= 1;
626 assert (frac[fracsize - 1] < 10);
628 exponent = exp10;
630 else
632 /* This is a special case. We don't need a factor because the
633 numbers are in the range of 0.0 <= fp < 8.0. We simply
634 shift it to the right place and divide it by 1.0 to get the
635 leading digit. (Of course this division is not really made.) */
636 assert (0 <= exponent && exponent < 3 &&
637 exponent + to_shift < BITS_PER_MP_LIMB);
639 /* Now shift the input value to its right place. */
640 cy = __mpn_lshift (frac, fp_input, fracsize, (exponent + to_shift));
641 frac[fracsize++] = cy;
642 exponent = 0;
646 int width = info->width;
647 char *buffer, *startp, *cp;
648 int chars_needed;
649 int expscale;
650 int intdig_max, intdig_no = 0;
651 int fracdig_min, fracdig_max, fracdig_no = 0;
652 int dig_max;
653 int significant;
655 if (tolower (info->spec) == 'e')
657 type = info->spec;
658 intdig_max = 1;
659 fracdig_min = fracdig_max = info->prec < 0 ? 6 : info->prec;
660 chars_needed = 1 + 1 + fracdig_max + 1 + 1 + 4;
661 /* d . ddd e +- ddd */
662 dig_max = INT_MAX; /* Unlimited. */
663 significant = 1; /* Does not matter here. */
665 else if (info->spec == 'f')
667 type = 'f';
668 fracdig_min = fracdig_max = info->prec < 0 ? 6 : info->prec;
669 if (expsign == 0)
671 intdig_max = exponent + 1;
672 /* This can be really big! */ /* XXX Maybe malloc if too big? */
673 chars_needed = exponent + 1 + 1 + fracdig_max;
675 else
677 intdig_max = 1;
678 chars_needed = 1 + 1 + fracdig_max;
680 dig_max = INT_MAX; /* Unlimited. */
681 significant = 1; /* Does not matter here. */
683 else
685 dig_max = info->prec < 0 ? 6 : (info->prec == 0 ? 1 : info->prec);
686 if ((expsign == 0 && exponent >= dig_max)
687 || (expsign != 0 && exponent > 4))
689 type = isupper (info->spec) ? 'E' : 'e';
690 fracdig_max = dig_max - 1;
691 intdig_max = 1;
692 chars_needed = 1 + 1 + fracdig_max + 1 + 1 + 4;
694 else
696 type = 'f';
697 intdig_max = expsign == 0 ? exponent + 1 : 0;
698 fracdig_max = dig_max - intdig_max;
699 /* We need space for the significant digits and perhaps for
700 leading zeros when < 1.0. Pessimistic guess: dig_max. */
701 chars_needed = dig_max + dig_max + 1;
703 fracdig_min = info->alt ? fracdig_max : 0;
704 significant = 0; /* We count significant digits. */
707 if (grouping)
708 /* Guess the number of groups we will make, and thus how
709 many spaces we need for separator characters. */
710 chars_needed += guess_grouping (intdig_max, grouping, thousands_sep);
712 /* Allocate buffer for output. We need two more because while rounding
713 it is possible that we need two more characters in front of all the
714 other output. */
715 buffer = alloca (2 + chars_needed);
716 cp = startp = buffer + 2; /* Let room for rounding. */
718 /* Do the real work: put digits in allocated buffer. */
719 if (expsign == 0 || type != 'f')
721 assert (expsign == 0 || intdig_max == 1);
722 while (intdig_no < intdig_max)
724 ++intdig_no;
725 *cp++ = hack_digit ();
727 significant = 1;
728 if (info->alt
729 || fracdig_min > 0
730 || (fracdig_max > 0 && (fracsize > 1 || frac[0] != 0)))
731 *cp++ = decimal;
733 else
735 /* |fp| < 1.0 and the selected type is 'f', so put "0."
736 in the buffer. */
737 *cp++ = '0';
738 --exponent;
739 *cp++ = decimal;
742 /* Generate the needed number of fractional digits. */
743 while (fracdig_no < fracdig_min
744 || (fracdig_no < fracdig_max && (fracsize > 1 || frac[0] != 0)))
746 ++fracdig_no;
747 *cp = hack_digit ();
748 if (*cp != '0')
749 significant = 1;
750 else if (significant == 0)
752 ++fracdig_max;
753 if (fracdig_min > 0)
754 ++fracdig_min;
756 ++cp;
759 /* Do rounding. */
760 digit = hack_digit ();
761 if (digit > '4')
763 char *tp = cp;
765 if (digit == '5')
766 /* This is the critical case. */
767 if (fracsize == 1 && frac[0] == 0)
768 /* Rest of the number is zero -> round to even.
769 (IEEE 754-1985 4.1 says this is the default rounding.) */
770 if ((*(cp - 1) & 1) == 0)
771 goto do_expo;
773 if (fracdig_no > 0)
775 /* Process fractional digits. Terminate if not rounded or
776 radix character is reached. */
777 while (*--tp != decimal && *tp == '9')
778 *tp = '0';
779 if (*tp != decimal)
780 /* Round up. */
781 (*tp)++;
784 if (fracdig_no == 0 || *tp == decimal)
786 /* Round the integer digits. */
787 if (*(tp - 1) == decimal)
788 --tp;
790 while (--tp >= startp && *tp == '9')
791 *tp = '0';
793 if (tp >= startp)
794 /* Round up. */
795 (*tp)++;
796 else
797 /* It is more citical. All digits were 9's. */
799 if (type != 'f')
801 *startp = '1';
802 exponent += expsign == 0 ? 1 : -1;
804 else if (intdig_no == dig_max)
806 /* This is the case where for type %g the number fits
807 really in the range for %f output but after rounding
808 the number of digits is too big. */
809 *--startp = decimal;
810 *--startp = '1';
812 if (info->alt || fracdig_no > 0)
814 /* Overwrite the old radix character. */
815 startp[intdig_no + 2] = '0';
816 ++fracdig_no;
819 fracdig_no += intdig_no;
820 intdig_no = 1;
821 fracdig_max = intdig_max - intdig_no;
822 ++exponent;
823 /* Now we must print the exponent. */
824 type = isupper (info->spec) ? 'E' : 'e';
826 else
828 /* We can simply add another another digit before the
829 radix. */
830 *--startp = '1';
831 ++intdig_no;
834 /* While rounding the number of digits can change.
835 If the number now exceeds the limits remove some
836 fractional digits. */
837 if (intdig_no + fracdig_no > dig_max)
839 cp -= intdig_no + fracdig_no - dig_max;
840 fracdig_no -= intdig_no + fracdig_no - dig_max;
846 do_expo:
847 /* Now remove unnecessary '0' at the end of the string. */
848 while (fracdig_no > fracdig_min && *(cp - 1) == '0')
850 --cp;
851 --fracdig_no;
853 /* If we eliminate all fractional digits we perhaps also can remove
854 the radix character. */
855 if (fracdig_no == 0 && !info->alt && *(cp - 1) == decimal)
856 --cp;
858 if (grouping)
859 /* Add in separator characters, overwriting the same buffer. */
860 cp = group_number (startp, cp, intdig_no, grouping, thousands_sep);
862 /* Write the exponent if it is needed. */
863 if (type != 'f')
865 *cp++ = type;
866 *cp++ = expsign ? '-' : '+';
868 /* Find the magnitude of the exponent. */
869 expscale = 10;
870 while (expscale <= exponent)
871 expscale *= 10;
873 if (exponent < 10)
874 /* Exponent always has at least two digits. */
875 *cp++ = '0';
876 else
879 expscale /= 10;
880 *cp++ = '0' + (exponent / expscale);
881 exponent %= expscale;
883 while (expscale > 10);
884 *cp++ = '0' + exponent;
887 /* Compute number of characters which must be filled with the padding
888 character. */
889 if (is_neg || info->showsign || info->space)
890 --width;
891 width -= cp - startp;
893 if (!info->left && info->pad != '0' && width > 0)
894 PADN (info->pad, width);
896 if (is_neg)
897 outchar ('-');
898 else if (info->showsign)
899 outchar ('+');
900 else if (info->space)
901 outchar (' ');
903 if (!info->left && info->pad == '0' && width > 0)
904 PADN ('0', width);
906 PRINT (startp, cp - startp);
908 if (info->left && width > 0)
909 PADN (info->pad, width);
911 return done;
914 /* Return the number of extra grouping characters that will be inserted
915 into a number with INTDIG_MAX integer digits. */
917 static unsigned int
918 guess_grouping (unsigned int intdig_max, const char *grouping, wchar_t sepchar)
920 unsigned int groups;
922 /* We treat all negative values like CHAR_MAX. */
924 if (*grouping == CHAR_MAX || *grouping <= 0)
925 /* No grouping should be done. */
926 return 0;
928 groups = 0;
929 while (intdig_max > (unsigned int) *grouping)
931 ++groups;
932 intdig_max -= *grouping++;
934 if (*grouping == CHAR_MAX || *grouping < 0)
935 /* No more grouping should be done. */
936 break;
937 else if (*grouping == 0)
939 /* Same grouping repeats. */
940 groups += intdig_max / grouping[-1];
941 break;
945 return groups;
948 /* Group the INTDIG_NO integer digits of the number in [BUF,BUFEND).
949 There is guaranteed enough space past BUFEND to extend it.
950 Return the new end of buffer. */
952 static char *
953 group_number (char *buf, char *bufend, unsigned int intdig_no,
954 const char *grouping, wchar_t thousands_sep)
956 unsigned int groups = guess_grouping (intdig_no, grouping, thousands_sep);
957 char *p;
959 if (groups == 0)
960 return bufend;
962 /* Move the fractional part down. */
963 memmove (buf + intdig_no + groups, buf + intdig_no,
964 bufend - (buf + intdig_no));
966 p = buf + intdig_no + groups - 1;
969 unsigned int len = *grouping++;
971 *p-- = buf[--intdig_no];
972 while (--len > 0);
973 *p-- = thousands_sep;
975 if (*grouping == CHAR_MAX || *grouping < 0)
976 /* No more grouping should be done. */
977 break;
978 else if (*grouping == 0)
979 /* Same grouping repeats. */
980 --grouping;
981 } while (intdig_no > (unsigned int) *grouping);
983 /* Copy the remaining ungrouped digits. */
985 *p-- = buf[--intdig_no];
986 while (p > buf);
988 return bufend + groups;