ack/lang/cem/libcc/gen/gcvt.c

66 lines
1.2 KiB
C
Raw Normal View History

1994-06-24 14:02:31 +00:00
/* $Id$ */
1987-01-27 15:57:55 +00:00
#ifndef NOFLOAT
extern char *ecvt();
1988-08-03 16:15:48 +00:00
#define NDIGINEXP(exp) (((exp) >= 100 || (exp) <= -100) ? 3 : 2)
1987-01-27 15:57:55 +00:00
char *
gcvt(value, ndigit, buf)
double value;
char *buf;
int ndigit;
1987-01-27 15:57:55 +00:00
{
int sign, dp;
register char *s1, *s2;
register int i;
register int nndigit = ndigit;
1987-01-27 15:57:55 +00:00
s1 = ecvt(value, ndigit, &dp, &sign);
s2 = buf;
if (sign) *s2++ = '-';
for (i = nndigit - 1; i > 0 && s1[i] == '0'; i--) nndigit--;
if (dp > ndigit || dp < -(NDIGINEXP(dp)+1)) {
1987-01-27 15:57:55 +00:00
/* Use E format, otherwise we need too many '0''s */
dp--;
*s2++ = *s1++;
*s2++ = '.';
while (--nndigit > 0) *s2++ = *s1++;
1987-01-27 15:57:55 +00:00
*s2++ = 'e';
if (dp < 0) {
*s2++ = '-';
dp = -dp;
}
else *s2++ = '+';
1988-08-03 16:15:48 +00:00
s2 += NDIGINEXP(dp);
*s2 = 0;
for (i = NDIGINEXP(dp); i > 0; i--) {
1987-01-27 15:57:55 +00:00
*--s2 = dp % 10 + '0';
dp /= 10;
}
return buf;
}
if (dp <= 0) {
if (*s1 != '0') {
/* otherwise the whole number is 0 */
*s2++ = '0';
1987-01-27 15:57:55 +00:00
*s2++ = '.';
}
while (dp < 0) {
dp++;
*s2++ = '0';
}
}
for (i = 1; i <= nndigit; i++) {
1987-01-27 15:57:55 +00:00
*s2++ = *s1++;
if (i == dp) *s2++ = '.';
}
if (i <= dp) {
while (i++ <= dp) *s2++ = '0';
*s2++ = '.';
}
if (s2[-1]=='.') s2--;
*s2 = '\0';
return buf;
}
#endif