1 /* $OpenBSD: ecvt.c,v 1.4 2005/08/08 08:05:36 espie Exp $ */
2
3 /*
4 * Copyright (c) 2002 Todd C. Miller <Todd.Miller@courtesan.com>
5 *
6 * Permission to use, copy, modify, and distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
9 *
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 *
18 * Sponsored in part by the Defense Advanced Research Projects
19 * Agency (DARPA) and Air Force Research Laboratory, Air Force
20 * Materiel Command, USAF, under agreement number F39502-99-1-0512.
21 */
22
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <string.h>
26
27 extern char *__dtoa(double, int, int, int *, int *, char **);
28 static char *__cvt(double, int, int *, int *, int, int);
29
30 static char *
__cvt(double value,int ndigit,int * decpt,int * sign,int fmode,int pad)31 __cvt(double value, int ndigit, int *decpt, int *sign, int fmode, int pad)
32 {
33 static char *s;
34 char *p, *rve;
35 size_t siz;
36
37 if (ndigit == 0) {
38 *sign = value < 0.0;
39 *decpt = 0;
40 return ((char *)"");
41 }
42
43 if (s) {
44 free(s);
45 s = NULL;
46 }
47
48 if (ndigit < 0)
49 siz = -ndigit + 1;
50 else
51 siz = ndigit + 1;
52
53
54 /* __dtoa() doesn't allocate space for 0 so we do it by hand */
55 if (value == 0.0) {
56 *decpt = 1 - fmode; /* 1 for 'e', 0 for 'f' */
57 *sign = 0;
58 if ((rve = s = (char *)malloc(siz)) == NULL)
59 return(NULL);
60 *rve++ = '0';
61 *rve = '\0';
62 } else {
63 p = __dtoa(value, fmode + 2, ndigit, decpt, sign, &rve);
64 if (*decpt == 9999) {
65 /* Nan or Infinity */
66 *decpt = 0;
67 return(p);
68 }
69 /* make a local copy and adjust rve to be in terms of s */
70 if (pad && fmode)
71 siz += *decpt;
72 if ((s = (char *)malloc(siz)) == NULL)
73 return(NULL);
74 (void) strlcpy(s, p, siz);
75 rve = s + (rve - p);
76 }
77
78 /* Add trailing zeros (unless we got NaN or Inf) */
79 if (pad && *decpt != 9999) {
80 siz -= rve - s;
81 while (--siz)
82 *rve++ = '0';
83 *rve = '\0';
84 }
85
86 return(s);
87 }
88
89 char *
ecvt(double value,int ndigit,int * decpt,int * sign)90 ecvt(double value, int ndigit, int *decpt, int *sign)
91 {
92 return(__cvt(value, ndigit, decpt, sign, 0, 1));
93 }
94
95 char *
fcvt(double value,int ndigit,int * decpt,int * sign)96 fcvt(double value, int ndigit, int *decpt, int *sign)
97 {
98 return(__cvt(value, ndigit, decpt, sign, 1, 1));
99 }
100