1 /* Compatibility functions for floating point formatting, reentrant versions.
2 Copyright (C) 1995-2023 Free Software Foundation, Inc.
3 This file is part of the GNU C Library.
5 The GNU C Library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
10 The GNU C Library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public
16 License along with the GNU C Library; if not, see
17 <https://www.gnu.org/licenses/>. */
25 #include <sys/param.h>
26 #include <math_ldbl_opt.h>
29 # define SNPRINTF __snprintf
33 #define APPEND(a, b) APPEND2 (a, b)
34 #define APPEND2(a, b) a##b
37 __FCVT_R (FLOAT_TYPE value
, int ndigit
, int *decpt
, int *sign
,
38 char *buf
, size_t len
)
53 *sign
= signbit (value
) != 0;
59 /* Rounding to the left of the decimal point. */
62 FLOAT_TYPE new_value
= value
* 0.1;
77 /* Value is Inf or NaN. */
80 n
= SNPRINTF (buf
, len
, "%.*" FLOAT_FMT_FLAG
"f", MIN (ndigit
, NDIGIT_MAX
),
82 /* Check for a too small buffer. */
83 if (n
>= (ssize_t
) len
)
87 while (i
< n
&& isdigit (buf
[i
]))
92 /* Value is Inf or NaN. */
99 while (i
< n
&& !isdigit (buf
[i
]));
101 if (*decpt
== 1 && buf
[0] == '0' && value
!= 0.0)
103 /* We must not have leading zeroes. Strip them all out and
104 adjust *DECPT if necessary. */
106 while (i
< n
&& buf
[i
] == '0')
113 memmove (&buf
[MAX (*decpt
, 0)], &buf
[i
], n
- i
);
114 buf
[n
- (i
- MAX (*decpt
, 0))] = '\0';
120 if ((ssize_t
) --len
> n
)
122 while (left
-- > 0 && n
< (ssize_t
) len
)
132 __ECVT_R (FLOAT_TYPE value
, int ndigit
, int *decpt
, int *sign
,
133 char *buf
, size_t len
)
137 if (isfinite (value
) && value
!= 0.0)
139 /* Slow code that doesn't require -lm functions. */
146 /* For denormalized numbers the d < 1.0 case below won't work,
147 as f can overflow to +Inf. */
148 if (d
< FLOAT_MIN_10_NORM
)
150 value
/= FLOAT_MIN_10_NORM
;
155 exponent
+= FLOAT_MIN_10_EXP
;
175 while (d
>= f
* 10.0);
180 else if (value
== 0.0)
181 /* SUSv2 leaves it unspecified whether *DECPT is 0 or 1 for 0.0.
182 This could be changed to -1 if we want to return 0. */
185 if (ndigit
<= 0 && len
> 0)
189 *sign
= isfinite (value
) ? signbit (value
) != 0 : 0;
192 if (__FCVT_R (value
, MIN (ndigit
, NDIGIT_MAX
) - 1,
193 decpt
, sign
, buf
, len
))