1/* $NetBSD: g_dfmt.c,v 1.2 2008/03/21 23:13:48 christos Exp $ */
2
3/****************************************************************
4
5The author of this software is David M. Gay.
6
7Copyright (C) 1998 by Lucent Technologies
8All Rights Reserved
9
10Permission to use, copy, modify, and distribute this software and
11its documentation for any purpose and without fee is hereby
12granted, provided that the above copyright notice appear in all
13copies and that both that the copyright notice and this
14permission notice and warranty disclaimer appear in supporting
15documentation, and that the name of Lucent or any of its entities
16not be used in advertising or publicity pertaining to
17distribution of the software without specific, written prior
18permission.
19
20LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
21INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
22IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY
23SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
24WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
25IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
26ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
27THIS SOFTWARE.
28
29****************************************************************/
30
31/* Please send bug reports to David M. Gay (dmg at acm dot org,
32 * with " at " changed at "@" and " dot " changed to ".").	*/
33
34#include "gdtoaimp.h"
35
36 char*
37#ifdef KR_headers
38g_dfmt(buf, d, ndig, bufsize) char *buf; double *d; int ndig; size_t bufsize;
39#else
40g_dfmt(char *buf, double *d, int ndig, size_t bufsize)
41#endif
42{
43	static FPI fpi0 = { 53, 1-1023-53+1, 2046-1023-53+1, 1, 0 };
44	char *b, *s, *se;
45	ULong bits[2], *L, sign;
46	int decpt, ex, i, mode;
47#ifdef Honor_FLT_ROUNDS
48#include "gdtoa_fltrnds.h"
49#else
50#define fpi &fpi0
51#endif
52
53	if (ndig < 0)
54		ndig = 0;
55	if (bufsize < ndig + 10)
56		return 0;
57
58	L = (ULong*)d;
59	sign = L[_0] & 0x80000000L;
60	if ((L[_0] & 0x7ff00000) == 0x7ff00000) {
61		/* Infinity or NaN */
62		if (bufsize < 10)
63			return 0;
64		if (L[_0] & 0xfffff || L[_1]) {
65			return strcp(buf, "NaN");
66			}
67		b = buf;
68		if (sign)
69			*b++ = '-';
70		return strcp(b, "Infinity");
71		}
72	if (L[_1] == 0 && (L[_0] ^ sign) == 0 /*d == 0.*/) {
73		b = buf;
74#ifndef IGNORE_ZERO_SIGN
75		if (L[_0] & 0x80000000L)
76			*b++ = '-';
77#endif
78		*b++ = '0';
79		*b = 0;
80		return b;
81		}
82	bits[0] = L[_1];
83	bits[1] = L[_0] & 0xfffff;
84	if ( (ex = (L[_0] >> 20) & 0x7ff) !=0)
85		bits[1] |= 0x100000;
86	else
87		ex = 1;
88	ex -= 0x3ff + 52;
89	mode = 2;
90	if (ndig <= 0)
91		mode = 0;
92	i = STRTOG_Normal;
93	if (sign)
94		i = STRTOG_Normal | STRTOG_Neg;
95	s = gdtoa(fpi, ex, bits, &i, mode, ndig, &decpt, &se);
96	if (s == NULL)
97		return NULL;
98	return g__fmt(buf, s, se, decpt, sign, bufsize);
99	}
100