Upgrade MPFR from 2.4.1 to 2.4.2-p3 on the vendor branch.
[dragonfly.git] / contrib / mpfr / out_str.c
1 /* mpfr_out_str -- output a floating-point number to a stream
2
3 Copyright 1999, 2001, 2002, 2004, 2006, 2007, 2008, 2009 Free Software Foundation, Inc.
4 Contributed by the Arenaire and Cacao projects, INRIA.
5
6 This file is part of the GNU MPFR Library.
7
8 The GNU MPFR Library is free software; you can redistribute it and/or modify
9 it under the terms of the GNU Lesser General Public License as published by
10 the Free Software Foundation; either version 2.1 of the License, or (at your
11 option) any later version.
12
13 The GNU MPFR Library is distributed in the hope that it will be useful, but
14 WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
15 or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public
16 License for more details.
17
18 You should have received a copy of the GNU Lesser General Public License
19 along with the GNU MPFR Library; see the file COPYING.LIB.  If not, write to
20 the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,
21 MA 02110-1301, USA. */
22
23 #include "mpfr-impl.h"
24
25 size_t
26 mpfr_out_str (FILE *stream, int base, size_t n_digits, mpfr_srcptr op,
27               mp_rnd_t rnd_mode)
28 {
29   char *s, *s0;
30   size_t l;
31   mp_exp_t e;
32
33   MPFR_ASSERTN (base >= 2 && base <= 36);
34
35   /* when stream=NULL, output to stdout */
36   if (stream == NULL)
37     stream = stdout;
38
39   if (MPFR_IS_NAN(op))
40     {
41       fprintf (stream, "@NaN@");
42       return 3;
43     }
44
45   if (MPFR_IS_INF(op))
46     {
47       if (MPFR_SIGN(op) > 0)
48         {
49           fprintf (stream, "@Inf@");
50           return 3;
51         }
52       else
53         {
54           fprintf (stream, "-@Inf@");
55           return 4;
56         }
57     }
58
59   if (MPFR_IS_ZERO(op))
60     {
61       if (MPFR_SIGN(op) > 0)
62         {
63           fprintf(stream, "0");
64           return 1;
65         }
66       else
67         {
68           fprintf(stream, "-0");
69           return 2;
70         }
71     }
72
73   s = mpfr_get_str (NULL, &e, base, n_digits, op, rnd_mode);
74
75   s0 = s;
76   /* for op=3.1416 we have s = "31416" and e = 1 */
77
78   l = strlen (s) + 1; /* size of allocated block returned by mpfr_get_str
79                          - may be incorrect, as only an upper bound? */
80   if (*s == '-')
81     fputc (*s++, stream);
82
83   /* outputs mantissa */
84   fputc (*s++, stream); e--; /* leading digit */
85   fputc ((unsigned char) MPFR_DECIMAL_POINT, stream);
86   fputs (s, stream);         /* rest of mantissa */
87   (*__gmp_free_func) (s0, l);
88
89   /* outputs exponent */
90   if (e)
91     {
92       MPFR_ASSERTN(e >= LONG_MIN);
93       MPFR_ASSERTN(e <= LONG_MAX);
94       l += fprintf (stream, (base <= 10 ? "e%ld" : "@%ld"), (long) e);
95     }
96
97   return l;
98 }