File:  [gforth] / gforth / engine / ecvt.c
Revision 1.1: download - view: text, annotated - select for diffs
Wed May 21 20:40:07 1997 UTC (26 years, 11 months ago) by anton
Branches: MAIN
CVS tags: HEAD
jwilke's changes:
Moved many files to other directories
renamed many files
other changes unknown to me.

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

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