File:  [gforth] / gforth / Attic / ecvt.c
Revision 1.3: download - view: text, annotated - select for diffs
Tue Jan 24 17:31:19 1995 UTC (29 years, 3 months ago) by pazsan
Branches: MAIN
CVS tags: HEAD
cross.fs: Corrected bug on le machines
Minor changes on other files

    1: #include <math.h>
    2: 
    3: #define MAXCONV 0x40
    4: char scratch[MAXCONV];
    5: 
    6: char* ecvt(double x, int len, int* exp, int* sign)
    7: {
    8:    int i, j;
    9:    double z;
   10:    
   11:    if(len > (MAXCONV-1)) len = MAXCONV-1;
   12:    
   13:    if(x<0)
   14:      {
   15: 	*sign = 1;
   16: 	x = -x;
   17:      }
   18:    else
   19:      {
   20: 	*sign = 0;
   21:      }
   22: 
   23:    if(x==0)
   24: 	*exp=-1;
   25:    else
   26:      *exp=(int)floor(log10(x));
   27:    x = x / pow10((double)*exp);
   28:    
   29:    *exp += 1;
   30:    
   31:    for(i=0; i < len; i++)
   32:      {
   33: 	z=floor(x);
   34: 	scratch[i]='0'+(char)((int)z);
   35: 	x = (x-z)*10;
   36:      }
   37:    
   38:    if((x >= 5) && i)
   39:      {
   40: 	for(j=i-1; j>=0; j--)
   41: 	  {
   42: 	     if(scratch[j]!='9')
   43: 	       {
   44: 		  scratch[j]+=1; break;
   45: 	       }
   46: 	     else
   47: 	       {
   48: 		  scratch[j]='0';
   49: 	       }
   50: 	  }
   51: 	if(j==0)
   52: 	  {
   53: 	     scratch[0]='1';
   54: 	     *exp += 1;
   55: 	  }
   56:      }
   57:    
   58:    scratch[i]='\0';
   59:    
   60:    return scratch;
   61: }
   62: 
   63: #ifdef TEST
   64: int main(int argc, char ** argv)
   65: {
   66:    int a, b;
   67:    char * conv=ecvt(PI*1e10,20,&a,&b);
   68:    
   69:    printf("ecvt Test: %f -> %s, %d, %d\n",PI,conv,a,b);
   70: }
   71: #endif

FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>