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. */
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"
44 #define NDEBUG /* Undefine this for debugging assertions. */
47 /* This defines make it possible to use the same code for GNU C library and
48 the GNU I/O library. */
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
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. */
69 register CONST int outc = (ch); \
70 if (putc (outc, fp) == EOF) \
75 #define PRINT(ptr, len) \
78 register size_t outlen = (len); \
81 if (PUT (fp, ptr, outlen) != outlen) \
88 while (outlen-- > 0) \
93 #define PADN(ch, len) \
96 if (PAD (fp, ch, len) != len) \
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,
119 extern mp_size_t __mpn_extract_long_double (mp_ptr res_ptr, mp_size_t size,
120 int *expt, int *is_neg,
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,
135 /* The floating-point value to output. */
143 /* Locale-dependent representation of decimal point. */
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
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. */
159 /* The significant of the floting-point value in question */
161 /* and the exponent. */
163 /* Sign of the exponent. */
165 /* Sign of float number. */
168 /* Scaling factor. */
171 /* Temporary bignum value. */
174 /* Digit which is result of last hack_digit() call. */
177 /* The type of output format that will be used: 'e'/'E' or 'f'. */
180 /* Counter for number of written characters. */
183 /* General helper (carry limb). */
186 char hack_digit (void)
190 if (expsign != 0 && type == 'f' && exponent-- > 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;
200 if (fracsize < scalesize)
204 hi = __mpn_divmod (tmp, frac, fracsize, scale, scalesize);
205 tmp[fracsize - scalesize] = hi;
208 fracsize = __mpn_normal_size (frac, scalesize);
211 /* We're not prepared for an mpn variable with zero
218 cy = __mpn_mul_1 (frac, frac, fracsize, 10);
220 frac[fracsize++] = cy;
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);
235 grouping = _NL_CURRENT (LC_NUMERIC, GROUPING);
236 if (*grouping <= 0 || *grouping == CHAR_MAX)
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')
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))
262 else if (__isinfl (fpnum.ldbl))
265 is_neg = fpnum.ldbl < 0;
269 fracsize = __mpn_extract_long_double (fp_input,
271 sizeof (fp_input[0])),
274 to_shift = 1 + fracsize * BITS_PER_MP_LIMB - LDBL_MANT_DIG;
279 fpnum.dbl = *(const double *) args[0];
281 /* Check for special values: not a number or infinity. */
282 if (__isnan (fpnum.dbl))
287 else if (__isinf (fpnum.dbl))
290 is_neg = fpnum.dbl < 0;
294 fracsize = __mpn_extract_double (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;
304 int width = info->prec > info->width ? info->prec : info->width;
306 if (is_neg || info->showsign || info->space)
310 if (!info->left && width > 0)
315 else if (info->showsign)
317 else if (info->space)
322 if (info->left && width > 0)
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
349 int explog = LDBL_MAX_10_EXP_LOG;
351 const struct mp_power *tens = &_fpioconst_pow10[explog + 1];
354 if ((exponent + to_shift) % BITS_PER_MP_LIMB == 0)
356 MPN_COPY_DECR (frac + (exponent + to_shift) / BITS_PER_MP_LIMB,
358 fracsize += (exponent + to_shift) / BITS_PER_MP_LIMB;
362 cy = __mpn_lshift (frac + (exponent + to_shift) / BITS_PER_MP_LIMB,
364 (exponent + to_shift) % BITS_PER_MP_LIMB);
365 fracsize += (exponent + to_shift) / BITS_PER_MP_LIMB;
367 frac[fracsize++] = cy;
369 MPN_ZERO (frac, (exponent + to_shift) / BITS_PER_MP_LIMB);
371 assert (tens > &_fpioconst_pow10[0]);
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)
381 MPN_ASSIGN (tmp, tens->array);
384 cy = __mpn_mul (tmp, scale, scalesize,
385 tens->array + 2, tens->arraysize - 2);
386 tmpsize = scalesize + tens->arraysize - 2;
391 if (MPN_GE (frac, tmp))
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;
402 while (tens > &_fpioconst_pow10[0]);
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). */
411 /* Determine minimum number of zero bits at the end of
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]);
421 /* The highest bit of the scaling factor is already set. So
422 we only have to remove the trailing empty limbs. */
425 MPN_COPY_INCR (scale, scale + i, scalesize - i);
427 MPN_COPY_INCR (frac, frac + i, fracsize - i);
435 count_trailing_zeros (cnt_l, scale[i]);
439 count_trailing_zeros (cnt_l2, frac[i]);
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);
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
464 (void) __mpn_rshift (scale, scale + i, scalesize - i,
465 BITS_PER_MP_LIMB - cnt_h);
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;
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),
478 BITS_PER_MP_LIMB - cnt_h);
480 (void) __mpn_rshift (frac, frac + (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)
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));
502 exponent = -exponent;
504 assert (tens != &_fpioconst_pow10[0]);
509 if (exponent >= tens->m_expo)
511 int i, incr, cnt_h, cnt_l;
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,
520 cy = __mpn_mul (tmp, frac, fracsize,
521 &tens->array[2], tens->arraysize - 2);
522 tmpsize = fracsize + tens->arraysize - 2;
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)
539 topval[1] = 10 << (BITS_PER_MP_LIMB - 4 - cnt_h);
543 topval[0] = 10 << (BITS_PER_MP_LIMB - 4);
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
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. */
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;
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
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;
600 /* We can only save the memory of the limbs which
601 are zero. The non-zero parts occupy the same
604 (void) __mpn_rshift (frac, tmp + (i - 1),
606 BITS_PER_MP_LIMB - 1 - cnt_h);
607 fracsize = tmpsize - (i - 1);
610 used_limbs = fracsize - 1;
615 while (tens != &_fpioconst_pow10[1] && exponent > 0);
616 /* All factors but 10^-1 are tested now. */
619 cy = __mpn_mul_1 (tmp, frac, fracsize, 10);
621 assert (cy == 0 || tmp[tmpsize - 1] < 20);
623 (void) __mpn_rshift (frac, tmp, tmpsize, MIN (4, exponent));
626 assert (frac[fracsize - 1] < 10);
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;
646 int width = info->width;
647 char *buffer, *startp, *cp;
650 int intdig_max, intdig_no = 0;
651 int fracdig_min, fracdig_max, fracdig_no = 0;
655 if (tolower (info->spec) == 'e')
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')
668 fracdig_min = fracdig_max = info->prec < 0 ? 6 : info->prec;
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;
678 chars_needed = 1 + 1 + fracdig_max;
680 dig_max = INT_MAX; /* Unlimited. */
681 significant = 1; /* Does not matter here. */
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;
692 chars_needed = 1 + 1 + fracdig_max + 1 + 1 + 4;
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. */
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
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)
725 *cp++ = hack_digit ();
730 || (fracdig_max > 0 && (fracsize > 1 || frac[0] != 0)))
735 /* |fp| < 1.0 and the selected type is 'f', so put "0."
742 /* Generate the needed number of fractional digits. */
743 while (fracdig_no < fracdig_min
744 || (fracdig_no < fracdig_max && (fracsize > 1 || frac[0] != 0)))
750 else if (significant == 0)
760 digit = hack_digit ();
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)
775 /* Process fractional digits. Terminate if not rounded or
776 radix character is reached. */
777 while (*--tp != decimal && *tp == '9')
784 if (fracdig_no == 0 || *tp == decimal)
786 /* Round the integer digits. */
787 if (*(tp - 1) == decimal)
790 while (--tp >= startp && *tp == '9')
797 /* It is more citical. All digits were 9's. */
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. */
812 if (info->alt || fracdig_no > 0)
814 /* Overwrite the old radix character. */
815 startp[intdig_no + 2] = '0';
819 fracdig_no += intdig_no;
821 fracdig_max = intdig_max - intdig_no;
823 /* Now we must print the exponent. */
824 type = isupper (info->spec) ? 'E' : 'e';
828 /* We can simply add another another digit before the
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;
847 /* Now remove unnecessary '0' at the end of the string. */
848 while (fracdig_no > fracdig_min && *(cp - 1) == '0')
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)
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. */
866 *cp++ = expsign ? '-' : '+';
868 /* Find the magnitude of the exponent. */
870 while (expscale <= exponent)
874 /* Exponent always has at least two digits. */
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
889 if (is_neg || info->showsign || info->space)
891 width -= cp - startp;
893 if (!info->left && info->pad != '0' && width > 0)
894 PADN (info->pad, width);
898 else if (info->showsign)
900 else if (info->space)
903 if (!info->left && info->pad == '0' && width > 0)
906 PRINT (startp, cp - startp);
908 if (info->left && width > 0)
909 PADN (info->pad, width);
914 /* Return the number of extra grouping characters that will be inserted
915 into a number with INTDIG_MAX integer digits. */
918 guess_grouping (unsigned int intdig_max, const char *grouping, wchar_t sepchar)
922 /* We treat all negative values like CHAR_MAX. */
924 if (*grouping == CHAR_MAX || *grouping <= 0)
925 /* No grouping should be done. */
929 while (intdig_max > (unsigned int) *grouping)
932 intdig_max -= *grouping++;
934 if (*grouping == CHAR_MAX || *grouping < 0)
935 /* No more grouping should be done. */
937 else if (*grouping == 0)
939 /* Same grouping repeats. */
940 groups += intdig_max / grouping[-1];
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. */
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);
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];
973 *p-- = thousands_sep;
975 if (*grouping == CHAR_MAX || *grouping < 0)
976 /* No more grouping should be done. */
978 else if (*grouping == 0)
979 /* Same grouping repeats. */
981 } while (intdig_no > (unsigned int) *grouping);
983 /* Copy the remaining ungrouped digits. */
985 *p-- = buf[--intdig_no];
988 return bufend + groups;