3 * (C) Copyright Dec 29 1995, Edmond J. Breen.
5 * This code may be copied for personal, non-profit use only.
11 /*#define DBL_MIN_EXP -100 */
17 #include "stdliblocal.h"
19 char *fftoa(double d, char *str, int p, char type, int trunc)
22 * Convert a floating-point number into a
23 * formatted 'f','e' or 'E' type string.
24 * (c) Edmond J.Breen, March 1995.
25 * where: 'p' represents the precision
26 * i.e. the number of digits
27 * that will be placed after
29 * A precision of 0 suppresses
31 * 'type' is either 'f', 'e' or 'E'.
33 * 'e' -> [-]m.dddde+xx
35 * 'E' -> [-]m.ddddE+xx
37 * 'trunc' if trunc != 0 then trailing
38 * zeros will be removed.
39 * i.e. 'g' or 'G' format.
42 int i, j, width, spt, dec, prec;
48 str[0] = '-', s = &str[1], d = -d;
51 if (d >= 1) { /* collect integer part */
59 } while ((D /= 10) >= 1);
60 /* now reverse the string */
61 for (k = i, j = 0, k--; j < k; j++, k--) {
68 if (!dec) { /* check for numbers less than 1 */
69 if (type != 'f') { /* assume 'e' or 'E' format */
70 if (d != 0) { /* d == d might be a safety check? */
71 while ((d *= 10) < 1 && dec > DBL_MIN_EXP)
83 width = prec + (dec > 0 ? dec : 1);
87 M = DBL_EPSILON/(FLT_RADIX*2.0); /* precision value */
88 while(1) { /* now collect fraction */
93 if((i < width) && (d >= M && d <= (1-M)))
94 s[i++] = (char) j + '0';
100 s[i++] = (char) j + '0';
104 /* Have to round see ANSI176,13.9.5.2 */
105 if (!strround(s, width + 1)) /* watch for over flow */
106 s[0] = '1', width++, dec++;
108 if (p != 0) { /* add in decimal point */
116 for (i = width; i > spt; i--)
122 if (trunc) { /* remove trailing zeros */
123 while (width && s[width] == '0')
128 if (type != 'f') { /* add in exponent */
136 } else if (dec < 0) {
142 itoa(dec, &s[++width], 10);