Update.
[glibc.git] / stdio-common / printf_fp.c
blob0a2efb7891e7ea03010f96be26d41de27a2b0170
1 /* Floating point output for `printf'.
2 Copyright (C) 1995, 1996, 1997, 1998, 1999 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>
44 #include <wchar.h>
46 #ifndef NDEBUG
47 # define NDEBUG /* Undefine this for debugging assertions. */
48 #endif
49 #include <assert.h>
51 /* This defines make it possible to use the same code for GNU C library and
52 the GNU I/O library. */
53 #ifdef USE_IN_LIBIO
54 # define PUT(f, s, n) _IO_sputn (f, s, n)
55 # define PAD(f, c, n) (wide ? _IO_wpadn (f, c, n) : _IO_padn (f, c, n))
56 /* We use this file GNU C library and GNU I/O library. So make
57 names equal. */
58 # undef putc
59 # define putc(c, f) (wide \
60 ? _IO_putwc_unlocked (c, f) : _IO_putc_unlocked (c, f))
61 # define size_t _IO_size_t
62 # define FILE _IO_FILE
63 #else /* ! USE_IN_LIBIO */
64 # define PUT(f, s, n) fwrite (s, 1, n, f)
65 # define PAD(f, c, n) __printf_pad (f, c, n)
66 ssize_t __printf_pad __P ((FILE *, char pad, int n)); /* In vfprintf.c. */
67 #endif /* USE_IN_LIBIO */
69 /* Macros for doing the actual output. */
71 #define outchar(ch) \
72 do \
73 { \
74 register const int outc = (ch); \
75 if (putc (outc, fp) == EOF) \
76 return -1; \
77 ++done; \
78 } while (0)
80 #define PRINT(ptr, len) \
81 do \
82 { \
83 register size_t outlen = (len); \
84 if (len > 20) \
85 { \
86 if (PUT (fp, ptr, outlen) != outlen) \
87 return -1; \
88 ptr += outlen; \
89 done += outlen; \
90 } \
91 else \
92 { \
93 while (outlen-- > 0) \
94 outchar (*ptr++); \
95 } \
96 } while (0)
98 #define PADN(ch, len) \
99 do \
101 if (PAD (fp, ch, len) != len) \
102 return -1; \
103 done += len; \
105 while (0)
107 /* We use the GNU MP library to handle large numbers.
109 An MP variable occupies a varying number of entries in its array. We keep
110 track of this number for efficiency reasons. Otherwise we would always
111 have to process the whole array. */
112 #define MPN_VAR(name) mp_limb_t *name; mp_size_t name##size
114 #define MPN_ASSIGN(dst,src) \
115 memcpy (dst, src, (dst##size = src##size) * sizeof (mp_limb_t))
116 #define MPN_GE(u,v) \
117 (u##size > v##size || (u##size == v##size && __mpn_cmp (u, v, u##size) >= 0))
119 extern int __isinfl (long double), __isnanl (long double);
121 extern mp_size_t __mpn_extract_double (mp_ptr res_ptr, mp_size_t size,
122 int *expt, int *is_neg,
123 double value);
124 extern mp_size_t __mpn_extract_long_double (mp_ptr res_ptr, mp_size_t size,
125 int *expt, int *is_neg,
126 long double value);
127 extern unsigned int __guess_grouping (unsigned int intdig_max,
128 const char *grouping, wchar_t sepchar);
131 static char *group_number (char *buf, char *bufend, unsigned int intdig_no,
132 const char *grouping, wchar_t thousands_sep)
133 internal_function;
137 __printf_fp (FILE *fp,
138 const struct printf_info *info,
139 const void *const *args)
141 /* The floating-point value to output. */
142 union
144 double dbl;
145 __long_double_t ldbl;
147 fpnum;
149 /* Locale-dependent representation of decimal point. */
150 wchar_t decimal;
152 /* Locale-dependent thousands separator and grouping specification. */
153 wchar_t thousands_sep;
154 const char *grouping;
156 /* "NaN" or "Inf" for the special cases. */
157 const char *special = NULL;
159 /* We need just a few limbs for the input before shifting to the right
160 position. */
161 mp_limb_t fp_input[(LDBL_MANT_DIG + BITS_PER_MP_LIMB - 1) / BITS_PER_MP_LIMB];
162 /* We need to shift the contents of fp_input by this amount of bits. */
163 int to_shift = 0;
165 /* The fraction of the floting-point value in question */
166 MPN_VAR(frac);
167 /* and the exponent. */
168 int exponent;
169 /* Sign of the exponent. */
170 int expsign = 0;
171 /* Sign of float number. */
172 int is_neg = 0;
174 /* Scaling factor. */
175 MPN_VAR(scale);
177 /* Temporary bignum value. */
178 MPN_VAR(tmp);
180 /* Digit which is result of last hack_digit() call. */
181 int digit;
183 /* The type of output format that will be used: 'e'/'E' or 'f'. */
184 int type;
186 /* Counter for number of written characters. */
187 int done = 0;
189 /* General helper (carry limb). */
190 mp_limb_t cy;
192 /* Nonzero if this is output on a wide character stream. */
193 int wide = info->wide;
195 char hack_digit (void)
197 mp_limb_t hi;
199 if (expsign != 0 && type == 'f' && exponent-- > 0)
200 hi = 0;
201 else if (scalesize == 0)
203 hi = frac[fracsize - 1];
204 cy = __mpn_mul_1 (frac, frac, fracsize - 1, 10);
205 frac[fracsize - 1] = cy;
207 else
209 if (fracsize < scalesize)
210 hi = 0;
211 else
213 hi = mpn_divmod (tmp, frac, fracsize, scale, scalesize);
214 tmp[fracsize - scalesize] = hi;
215 hi = tmp[0];
217 fracsize = scalesize;
218 while (fracsize != 0 && frac[fracsize - 1] == 0)
219 --fracsize;
220 if (fracsize == 0)
222 /* We're not prepared for an mpn variable with zero
223 limbs. */
224 fracsize = 1;
225 return '0' + hi;
229 cy = __mpn_mul_1 (frac, frac, fracsize, 10);
230 if (cy != 0)
231 frac[fracsize++] = cy;
234 return '0' + hi;
238 /* Figure out the decimal point character. */
239 if (info->extra == 0)
241 mbstate_t state;
243 memset (&state, '\0', sizeof (state));
244 if (__mbrtowc (&decimal, _NL_CURRENT (LC_NUMERIC, DECIMAL_POINT),
245 strlen (_NL_CURRENT (LC_NUMERIC, DECIMAL_POINT)),
246 &state) <= 0)
247 decimal = (wchar_t) *_NL_CURRENT (LC_NUMERIC, DECIMAL_POINT);
249 else
251 mbstate_t state;
253 memset (&state, '\0', sizeof (state));
254 if (__mbrtowc (&decimal, _NL_CURRENT (LC_MONETARY, MON_DECIMAL_POINT),
255 strlen (_NL_CURRENT (LC_MONETARY, MON_DECIMAL_POINT)),
256 &state) <= 0)
257 decimal = (wchar_t) *_NL_CURRENT (LC_MONETARY, MON_DECIMAL_POINT);
259 /* Give default value. */
260 if (decimal == L'\0')
261 decimal = L'.';
264 if (info->group)
266 if (info->extra == 0)
267 grouping = _NL_CURRENT (LC_NUMERIC, GROUPING);
268 else
269 grouping = _NL_CURRENT (LC_MONETARY, MON_GROUPING);
271 if (*grouping <= 0 || *grouping == CHAR_MAX)
272 grouping = NULL;
273 else
275 /* Figure out the thousands separator character. */
276 if (info->extra == 0)
278 mbstate_t state;
280 memset (&state, '\0', sizeof (state));
281 if (__mbrtowc (&thousands_sep, _NL_CURRENT (LC_NUMERIC,
282 THOUSANDS_SEP),
283 strlen (_NL_CURRENT (LC_NUMERIC, THOUSANDS_SEP)),
284 &state) <= 0)
285 thousands_sep = (wchar_t) *_NL_CURRENT (LC_NUMERIC,
286 THOUSANDS_SEP);
288 else
290 mbstate_t state;
292 memset (&state, '\0', sizeof (state));
293 if (__mbrtowc (&thousands_sep, _NL_CURRENT (LC_MONETARY,
294 MON_THOUSANDS_SEP),
295 strlen (_NL_CURRENT (LC_MONETARY,
296 MON_THOUSANDS_SEP)),
297 &state) <= 0)
298 thousands_sep = (wchar_t) *_NL_CURRENT (LC_MONETARY,
299 MON_THOUSANDS_SEP);
302 if (thousands_sep == L'\0')
303 grouping = NULL;
306 else
307 grouping = NULL;
309 /* Fetch the argument value. */
310 #ifndef __NO_LONG_DOUBLE_MATH
311 if (info->is_long_double && sizeof (long double) > sizeof (double))
313 fpnum.ldbl = *(const long double *) args[0];
315 /* Check for special values: not a number or infinity. */
316 if (__isnanl (fpnum.ldbl))
318 special = isupper (info->spec) ? "NAN" : "nan";
319 is_neg = 0;
321 else if (__isinfl (fpnum.ldbl))
323 special = isupper (info->spec) ? "INF" : "inf";
324 is_neg = fpnum.ldbl < 0;
326 else
328 fracsize = __mpn_extract_long_double (fp_input,
329 (sizeof (fp_input) /
330 sizeof (fp_input[0])),
331 &exponent, &is_neg,
332 fpnum.ldbl);
333 to_shift = 1 + fracsize * BITS_PER_MP_LIMB - LDBL_MANT_DIG;
336 else
337 #endif /* no long double */
339 fpnum.dbl = *(const double *) args[0];
341 /* Check for special values: not a number or infinity. */
342 if (__isnan (fpnum.dbl))
344 special = isupper (info->spec) ? "NAN" : "nan";
345 is_neg = 0;
347 else if (__isinf (fpnum.dbl))
349 special = isupper (info->spec) ? "INF" : "inf";
350 is_neg = fpnum.dbl < 0;
352 else
354 fracsize = __mpn_extract_double (fp_input,
355 (sizeof (fp_input)
356 / sizeof (fp_input[0])),
357 &exponent, &is_neg, fpnum.dbl);
358 to_shift = 1 + fracsize * BITS_PER_MP_LIMB - DBL_MANT_DIG;
362 if (special)
364 int width = info->width;
366 if (is_neg || info->showsign || info->space)
367 --width;
368 width -= 3;
370 if (!info->left && width > 0)
371 PADN (' ', width);
373 if (is_neg)
374 outchar ('-');
375 else if (info->showsign)
376 outchar ('+');
377 else if (info->space)
378 outchar (' ');
380 PRINT (special, 3);
382 if (info->left && width > 0)
383 PADN (' ', width);
385 return done;
389 /* We need three multiprecision variables. Now that we have the exponent
390 of the number we can allocate the needed memory. It would be more
391 efficient to use variables of the fixed maximum size but because this
392 would be really big it could lead to memory problems. */
394 mp_size_t bignum_size = ((ABS (exponent) + BITS_PER_MP_LIMB - 1)
395 / BITS_PER_MP_LIMB + 4) * sizeof (mp_limb_t);
396 frac = (mp_limb_t *) alloca (bignum_size);
397 tmp = (mp_limb_t *) alloca (bignum_size);
398 scale = (mp_limb_t *) alloca (bignum_size);
401 /* We now have to distinguish between numbers with positive and negative
402 exponents because the method used for the one is not applicable/efficient
403 for the other. */
404 scalesize = 0;
405 if (exponent > 2)
407 /* |FP| >= 8.0. */
408 int scaleexpo = 0;
409 int explog = LDBL_MAX_10_EXP_LOG;
410 int exp10 = 0;
411 const struct mp_power *powers = &_fpioconst_pow10[explog + 1];
412 int cnt_h, cnt_l, i;
414 if ((exponent + to_shift) % BITS_PER_MP_LIMB == 0)
416 MPN_COPY_DECR (frac + (exponent + to_shift) / BITS_PER_MP_LIMB,
417 fp_input, fracsize);
418 fracsize += (exponent + to_shift) / BITS_PER_MP_LIMB;
420 else
422 cy = __mpn_lshift (frac + (exponent + to_shift) / BITS_PER_MP_LIMB,
423 fp_input, fracsize,
424 (exponent + to_shift) % BITS_PER_MP_LIMB);
425 fracsize += (exponent + to_shift) / BITS_PER_MP_LIMB;
426 if (cy)
427 frac[fracsize++] = cy;
429 MPN_ZERO (frac, (exponent + to_shift) / BITS_PER_MP_LIMB);
431 assert (powers > &_fpioconst_pow10[0]);
434 --powers;
436 /* The number of the product of two binary numbers with n and m
437 bits respectively has m+n or m+n-1 bits. */
438 if (exponent >= scaleexpo + powers->p_expo - 1)
440 if (scalesize == 0)
442 #ifndef __NO_LONG_DOUBLE_MATH
443 if (LDBL_MANT_DIG > _FPIO_CONST_OFFSET * BITS_PER_MP_LIMB
444 && info->is_long_double)
446 #define _FPIO_CONST_SHIFT \
447 (((LDBL_MANT_DIG + BITS_PER_MP_LIMB - 1) / BITS_PER_MP_LIMB) \
448 - _FPIO_CONST_OFFSET)
449 /* 64bit const offset is not enough for
450 IEEE quad long double. */
451 tmpsize = powers->arraysize + _FPIO_CONST_SHIFT;
452 memcpy (tmp + _FPIO_CONST_SHIFT,
453 &__tens[powers->arrayoff],
454 tmpsize * sizeof (mp_limb_t));
455 MPN_ZERO (tmp, _FPIO_CONST_SHIFT);
457 else
458 #endif
460 tmpsize = powers->arraysize;
461 memcpy (tmp, &__tens[powers->arrayoff],
462 tmpsize * sizeof (mp_limb_t));
465 else
467 cy = __mpn_mul (tmp, scale, scalesize,
468 &__tens[powers->arrayoff
469 + _FPIO_CONST_OFFSET],
470 powers->arraysize - _FPIO_CONST_OFFSET);
471 tmpsize = scalesize + powers->arraysize - _FPIO_CONST_OFFSET;
472 if (cy == 0)
473 --tmpsize;
476 if (MPN_GE (frac, tmp))
478 int cnt;
479 MPN_ASSIGN (scale, tmp);
480 count_leading_zeros (cnt, scale[scalesize - 1]);
481 scaleexpo = (scalesize - 2) * BITS_PER_MP_LIMB - cnt - 1;
482 exp10 |= 1 << explog;
485 --explog;
487 while (powers > &_fpioconst_pow10[0]);
488 exponent = exp10;
490 /* Optimize number representations. We want to represent the numbers
491 with the lowest number of bytes possible without losing any
492 bytes. Also the highest bit in the scaling factor has to be set
493 (this is a requirement of the MPN division routines). */
494 if (scalesize > 0)
496 /* Determine minimum number of zero bits at the end of
497 both numbers. */
498 for (i = 0; scale[i] == 0 && frac[i] == 0; i++)
501 /* Determine number of bits the scaling factor is misplaced. */
502 count_leading_zeros (cnt_h, scale[scalesize - 1]);
504 if (cnt_h == 0)
506 /* The highest bit of the scaling factor is already set. So
507 we only have to remove the trailing empty limbs. */
508 if (i > 0)
510 MPN_COPY_INCR (scale, scale + i, scalesize - i);
511 scalesize -= i;
512 MPN_COPY_INCR (frac, frac + i, fracsize - i);
513 fracsize -= i;
516 else
518 if (scale[i] != 0)
520 count_trailing_zeros (cnt_l, scale[i]);
521 if (frac[i] != 0)
523 int cnt_l2;
524 count_trailing_zeros (cnt_l2, frac[i]);
525 if (cnt_l2 < cnt_l)
526 cnt_l = cnt_l2;
529 else
530 count_trailing_zeros (cnt_l, frac[i]);
532 /* Now shift the numbers to their optimal position. */
533 if (i == 0 && BITS_PER_MP_LIMB - cnt_h > cnt_l)
535 /* We cannot save any memory. So just roll both numbers
536 so that the scaling factor has its highest bit set. */
538 (void) __mpn_lshift (scale, scale, scalesize, cnt_h);
539 cy = __mpn_lshift (frac, frac, fracsize, cnt_h);
540 if (cy != 0)
541 frac[fracsize++] = cy;
543 else if (BITS_PER_MP_LIMB - cnt_h <= cnt_l)
545 /* We can save memory by removing the trailing zero limbs
546 and by packing the non-zero limbs which gain another
547 free one. */
549 (void) __mpn_rshift (scale, scale + i, scalesize - i,
550 BITS_PER_MP_LIMB - cnt_h);
551 scalesize -= i + 1;
552 (void) __mpn_rshift (frac, frac + i, fracsize - i,
553 BITS_PER_MP_LIMB - cnt_h);
554 fracsize -= frac[fracsize - i - 1] == 0 ? i + 1 : i;
556 else
558 /* We can only save the memory of the limbs which are zero.
559 The non-zero parts occupy the same number of limbs. */
561 (void) __mpn_rshift (scale, scale + (i - 1),
562 scalesize - (i - 1),
563 BITS_PER_MP_LIMB - cnt_h);
564 scalesize -= i;
565 (void) __mpn_rshift (frac, frac + (i - 1),
566 fracsize - (i - 1),
567 BITS_PER_MP_LIMB - cnt_h);
568 fracsize -= frac[fracsize - (i - 1) - 1] == 0 ? i : i - 1;
573 else if (exponent < 0)
575 /* |FP| < 1.0. */
576 int exp10 = 0;
577 int explog = LDBL_MAX_10_EXP_LOG;
578 const struct mp_power *powers = &_fpioconst_pow10[explog + 1];
579 mp_size_t used_limbs = fracsize - 1;
581 /* Now shift the input value to its right place. */
582 cy = __mpn_lshift (frac, fp_input, fracsize, to_shift);
583 frac[fracsize++] = cy;
584 assert (cy == 1 || (frac[fracsize - 2] == 0 && frac[0] == 0));
586 expsign = 1;
587 exponent = -exponent;
589 assert (powers != &_fpioconst_pow10[0]);
592 --powers;
594 if (exponent >= powers->m_expo)
596 int i, incr, cnt_h, cnt_l;
597 mp_limb_t topval[2];
599 /* The __mpn_mul function expects the first argument to be
600 bigger than the second. */
601 if (fracsize < powers->arraysize - _FPIO_CONST_OFFSET)
602 cy = __mpn_mul (tmp, &__tens[powers->arrayoff
603 + _FPIO_CONST_OFFSET],
604 powers->arraysize - _FPIO_CONST_OFFSET,
605 frac, fracsize);
606 else
607 cy = __mpn_mul (tmp, frac, fracsize,
608 &__tens[powers->arrayoff + _FPIO_CONST_OFFSET],
609 powers->arraysize - _FPIO_CONST_OFFSET);
610 tmpsize = fracsize + powers->arraysize - _FPIO_CONST_OFFSET;
611 if (cy == 0)
612 --tmpsize;
614 count_leading_zeros (cnt_h, tmp[tmpsize - 1]);
615 incr = (tmpsize - fracsize) * BITS_PER_MP_LIMB
616 + BITS_PER_MP_LIMB - 1 - cnt_h;
618 assert (incr <= powers->p_expo);
620 /* If we increased the exponent by exactly 3 we have to test
621 for overflow. This is done by comparing with 10 shifted
622 to the right position. */
623 if (incr == exponent + 3)
625 if (cnt_h <= BITS_PER_MP_LIMB - 4)
627 topval[0] = 0;
628 topval[1]
629 = ((mp_limb_t) 10) << (BITS_PER_MP_LIMB - 4 - cnt_h);
631 else
633 topval[0] = ((mp_limb_t) 10) << (BITS_PER_MP_LIMB - 4);
634 topval[1] = 0;
635 (void) __mpn_lshift (topval, topval, 2,
636 BITS_PER_MP_LIMB - cnt_h);
640 /* We have to be careful when multiplying the last factor.
641 If the result is greater than 1.0 be have to test it
642 against 10.0. If it is greater or equal to 10.0 the
643 multiplication was not valid. This is because we cannot
644 determine the number of bits in the result in advance. */
645 if (incr < exponent + 3
646 || (incr == exponent + 3 &&
647 (tmp[tmpsize - 1] < topval[1]
648 || (tmp[tmpsize - 1] == topval[1]
649 && tmp[tmpsize - 2] < topval[0]))))
651 /* The factor is right. Adapt binary and decimal
652 exponents. */
653 exponent -= incr;
654 exp10 |= 1 << explog;
656 /* If this factor yields a number greater or equal to
657 1.0, we must not shift the non-fractional digits down. */
658 if (exponent < 0)
659 cnt_h += -exponent;
661 /* Now we optimize the number representation. */
662 for (i = 0; tmp[i] == 0; ++i);
663 if (cnt_h == BITS_PER_MP_LIMB - 1)
665 MPN_COPY (frac, tmp + i, tmpsize - i);
666 fracsize = tmpsize - i;
668 else
670 count_trailing_zeros (cnt_l, tmp[i]);
672 /* Now shift the numbers to their optimal position. */
673 if (i == 0 && BITS_PER_MP_LIMB - 1 - cnt_h > cnt_l)
675 /* We cannot save any memory. Just roll the
676 number so that the leading digit is in a
677 separate limb. */
679 cy = __mpn_lshift (frac, tmp, tmpsize, cnt_h + 1);
680 fracsize = tmpsize + 1;
681 frac[fracsize - 1] = cy;
683 else if (BITS_PER_MP_LIMB - 1 - cnt_h <= cnt_l)
685 (void) __mpn_rshift (frac, tmp + i, tmpsize - i,
686 BITS_PER_MP_LIMB - 1 - cnt_h);
687 fracsize = tmpsize - i;
689 else
691 /* We can only save the memory of the limbs which
692 are zero. The non-zero parts occupy the same
693 number of limbs. */
695 (void) __mpn_rshift (frac, tmp + (i - 1),
696 tmpsize - (i - 1),
697 BITS_PER_MP_LIMB - 1 - cnt_h);
698 fracsize = tmpsize - (i - 1);
701 used_limbs = fracsize - 1;
704 --explog;
706 while (powers != &_fpioconst_pow10[1] && exponent > 0);
707 /* All factors but 10^-1 are tested now. */
708 if (exponent > 0)
710 int cnt_l;
712 cy = __mpn_mul_1 (tmp, frac, fracsize, 10);
713 tmpsize = fracsize;
714 assert (cy == 0 || tmp[tmpsize - 1] < 20);
716 count_trailing_zeros (cnt_l, tmp[0]);
717 if (cnt_l < MIN (4, exponent))
719 cy = __mpn_lshift (frac, tmp, tmpsize,
720 BITS_PER_MP_LIMB - MIN (4, exponent));
721 if (cy != 0)
722 frac[tmpsize++] = cy;
724 else
725 (void) __mpn_rshift (frac, tmp, tmpsize, MIN (4, exponent));
726 fracsize = tmpsize;
727 exp10 |= 1;
728 assert (frac[fracsize - 1] < 10);
730 exponent = exp10;
732 else
734 /* This is a special case. We don't need a factor because the
735 numbers are in the range of 0.0 <= fp < 8.0. We simply
736 shift it to the right place and divide it by 1.0 to get the
737 leading digit. (Of course this division is not really made.) */
738 assert (0 <= exponent && exponent < 3 &&
739 exponent + to_shift < BITS_PER_MP_LIMB);
741 /* Now shift the input value to its right place. */
742 cy = __mpn_lshift (frac, fp_input, fracsize, (exponent + to_shift));
743 frac[fracsize++] = cy;
744 exponent = 0;
748 int width = info->width;
749 char *buffer, *startp, *cp;
750 int chars_needed;
751 int expscale;
752 int intdig_max, intdig_no = 0;
753 int fracdig_min, fracdig_max, fracdig_no = 0;
754 int dig_max;
755 int significant;
757 if (_tolower (info->spec) == 'e')
759 type = info->spec;
760 intdig_max = 1;
761 fracdig_min = fracdig_max = info->prec < 0 ? 6 : info->prec;
762 chars_needed = 1 + 1 + fracdig_max + 1 + 1 + 4;
763 /* d . ddd e +- ddd */
764 dig_max = INT_MAX; /* Unlimited. */
765 significant = 1; /* Does not matter here. */
767 else if (info->spec == 'f')
769 type = 'f';
770 fracdig_min = fracdig_max = info->prec < 0 ? 6 : info->prec;
771 if (expsign == 0)
773 intdig_max = exponent + 1;
774 /* This can be really big! */ /* XXX Maybe malloc if too big? */
775 chars_needed = exponent + 1 + 1 + fracdig_max;
777 else
779 intdig_max = 1;
780 chars_needed = 1 + 1 + fracdig_max;
782 dig_max = INT_MAX; /* Unlimited. */
783 significant = 1; /* Does not matter here. */
785 else
787 dig_max = info->prec < 0 ? 6 : (info->prec == 0 ? 1 : info->prec);
788 if ((expsign == 0 && exponent >= dig_max)
789 || (expsign != 0 && exponent > 4))
791 if ('g' - 'G' == 'e' - 'E')
792 type = 'E' + (info->spec - 'G');
793 else
794 type = isupper (info->spec) ? 'E' : 'e';
795 fracdig_max = dig_max - 1;
796 intdig_max = 1;
797 chars_needed = 1 + 1 + fracdig_max + 1 + 1 + 4;
799 else
801 type = 'f';
802 intdig_max = expsign == 0 ? exponent + 1 : 0;
803 fracdig_max = dig_max - intdig_max;
804 /* We need space for the significant digits and perhaps for
805 leading zeros when < 1.0. Pessimistic guess: dig_max. */
806 chars_needed = dig_max + dig_max + 1;
808 fracdig_min = info->alt ? fracdig_max : 0;
809 significant = 0; /* We count significant digits. */
812 if (grouping)
813 /* Guess the number of groups we will make, and thus how
814 many spaces we need for separator characters. */
815 chars_needed += __guess_grouping (intdig_max, grouping, thousands_sep);
817 /* Allocate buffer for output. We need two more because while rounding
818 it is possible that we need two more characters in front of all the
819 other output. */
820 buffer = alloca (2 + chars_needed);
821 cp = startp = buffer + 2; /* Let room for rounding. */
823 /* Do the real work: put digits in allocated buffer. */
824 if (expsign == 0 || type != 'f')
826 assert (expsign == 0 || intdig_max == 1);
827 while (intdig_no < intdig_max)
829 ++intdig_no;
830 *cp++ = hack_digit ();
832 significant = 1;
833 if (info->alt
834 || fracdig_min > 0
835 || (fracdig_max > 0 && (fracsize > 1 || frac[0] != 0)))
836 *cp++ = decimal;
838 else
840 /* |fp| < 1.0 and the selected type is 'f', so put "0."
841 in the buffer. */
842 *cp++ = '0';
843 --exponent;
844 *cp++ = decimal;
847 /* Generate the needed number of fractional digits. */
848 while (fracdig_no < fracdig_min
849 || (fracdig_no < fracdig_max && (fracsize > 1 || frac[0] != 0)))
851 ++fracdig_no;
852 *cp = hack_digit ();
853 if (*cp != '0')
854 significant = 1;
855 else if (significant == 0)
857 ++fracdig_max;
858 if (fracdig_min > 0)
859 ++fracdig_min;
861 ++cp;
864 /* Do rounding. */
865 digit = hack_digit ();
866 if (digit > '4')
868 char *tp = cp;
870 if (digit == '5' && (*(cp - 1) & 1) == 0)
872 /* This is the critical case. */
873 if (fracsize == 1 && frac[0] == 0)
874 /* Rest of the number is zero -> round to even.
875 (IEEE 754-1985 4.1 says this is the default rounding.) */
876 goto do_expo;
877 else if (scalesize == 0)
879 /* Here we have to see whether all limbs are zero since no
880 normalization happened. */
881 size_t lcnt = fracsize;
882 while (lcnt >= 1 && frac[lcnt - 1] == 0)
883 --lcnt;
884 if (lcnt == 0)
885 /* Rest of the number is zero -> round to even.
886 (IEEE 754-1985 4.1 says this is the default rounding.) */
887 goto do_expo;
891 if (fracdig_no > 0)
893 /* Process fractional digits. Terminate if not rounded or
894 radix character is reached. */
895 while (*--tp != decimal && *tp == '9')
896 *tp = '0';
897 if (*tp != decimal)
898 /* Round up. */
899 (*tp)++;
902 if (fracdig_no == 0 || *tp == decimal)
904 /* Round the integer digits. */
905 if (*(tp - 1) == decimal)
906 --tp;
908 while (--tp >= startp && *tp == '9')
909 *tp = '0';
911 if (tp >= startp)
912 /* Round up. */
913 (*tp)++;
914 else
915 /* It is more critical. All digits were 9's. */
917 if (type != 'f')
919 *startp = '1';
920 exponent += expsign == 0 ? 1 : -1;
922 else if (intdig_no == dig_max)
924 /* This is the case where for type %g the number fits
925 really in the range for %f output but after rounding
926 the number of digits is too big. */
927 *--startp = decimal;
928 *--startp = '1';
930 if (info->alt || fracdig_no > 0)
932 /* Overwrite the old radix character. */
933 startp[intdig_no + 2] = '0';
934 ++fracdig_no;
937 fracdig_no += intdig_no;
938 intdig_no = 1;
939 fracdig_max = intdig_max - intdig_no;
940 ++exponent;
941 /* Now we must print the exponent. */
942 type = isupper (info->spec) ? 'E' : 'e';
944 else
946 /* We can simply add another another digit before the
947 radix. */
948 *--startp = '1';
949 ++intdig_no;
952 /* While rounding the number of digits can change.
953 If the number now exceeds the limits remove some
954 fractional digits. */
955 if (intdig_no + fracdig_no > dig_max)
957 cp -= intdig_no + fracdig_no - dig_max;
958 fracdig_no -= intdig_no + fracdig_no - dig_max;
964 do_expo:
965 /* Now remove unnecessary '0' at the end of the string. */
966 while (fracdig_no > fracdig_min && *(cp - 1) == '0')
968 --cp;
969 --fracdig_no;
971 /* If we eliminate all fractional digits we perhaps also can remove
972 the radix character. */
973 if (fracdig_no == 0 && !info->alt && *(cp - 1) == decimal)
974 --cp;
976 if (grouping)
977 /* Add in separator characters, overwriting the same buffer. */
978 cp = group_number (startp, cp, intdig_no, grouping, thousands_sep);
980 /* Write the exponent if it is needed. */
981 if (type != 'f')
983 *cp++ = type;
984 *cp++ = expsign ? '-' : '+';
986 /* Find the magnitude of the exponent. */
987 expscale = 10;
988 while (expscale <= exponent)
989 expscale *= 10;
991 if (exponent < 10)
992 /* Exponent always has at least two digits. */
993 *cp++ = '0';
994 else
997 expscale /= 10;
998 *cp++ = '0' + (exponent / expscale);
999 exponent %= expscale;
1001 while (expscale > 10);
1002 *cp++ = '0' + exponent;
1005 /* Compute number of characters which must be filled with the padding
1006 character. */
1007 if (is_neg || info->showsign || info->space)
1008 --width;
1009 width -= cp - startp;
1011 if (!info->left && info->pad != '0' && width > 0)
1012 PADN (info->pad, width);
1014 if (is_neg)
1015 outchar ('-');
1016 else if (info->showsign)
1017 outchar ('+');
1018 else if (info->space)
1019 outchar (' ');
1021 if (!info->left && info->pad == '0' && width > 0)
1022 PADN ('0', width);
1024 PRINT (startp, cp - startp);
1026 if (info->left && width > 0)
1027 PADN (info->pad, width);
1029 return done;
1032 /* Return the number of extra grouping characters that will be inserted
1033 into a number with INTDIG_MAX integer digits. */
1035 unsigned int
1036 __guess_grouping (unsigned int intdig_max, const char *grouping,
1037 wchar_t sepchar)
1039 unsigned int groups;
1041 /* We treat all negative values like CHAR_MAX. */
1043 if (*grouping == CHAR_MAX || *grouping <= 0)
1044 /* No grouping should be done. */
1045 return 0;
1047 groups = 0;
1048 while (intdig_max > (unsigned int) *grouping)
1050 ++groups;
1051 intdig_max -= *grouping++;
1053 if (*grouping == CHAR_MAX
1054 #if CHAR_MIN < 0
1055 || *grouping < 0
1056 #endif
1058 /* No more grouping should be done. */
1059 break;
1060 else if (*grouping == 0)
1062 /* Same grouping repeats. */
1063 groups += (intdig_max - 1) / grouping[-1];
1064 break;
1068 return groups;
1071 /* Group the INTDIG_NO integer digits of the number in [BUF,BUFEND).
1072 There is guaranteed enough space past BUFEND to extend it.
1073 Return the new end of buffer. */
1075 static char *
1076 internal_function
1077 group_number (char *buf, char *bufend, unsigned int intdig_no,
1078 const char *grouping, wchar_t thousands_sep)
1080 unsigned int groups = __guess_grouping (intdig_no, grouping, thousands_sep);
1081 char *p;
1083 if (groups == 0)
1084 return bufend;
1086 /* Move the fractional part down. */
1087 memmove (buf + intdig_no + groups, buf + intdig_no,
1088 bufend - (buf + intdig_no));
1090 p = buf + intdig_no + groups - 1;
1093 unsigned int len = *grouping++;
1095 *p-- = buf[--intdig_no];
1096 while (--len > 0);
1097 *p-- = thousands_sep;
1099 if (*grouping == CHAR_MAX
1100 #if CHAR_MIN < 0
1101 || *grouping < 0
1102 #endif
1104 /* No more grouping should be done. */
1105 break;
1106 else if (*grouping == 0)
1107 /* Same grouping repeats. */
1108 --grouping;
1109 } while (intdig_no > (unsigned int) *grouping);
1111 /* Copy the remaining ungrouped digits. */
1113 *p-- = buf[--intdig_no];
1114 while (p > buf);
1116 return bufend + groups;