File:  [gforth] / gforth / engine / ecvt.c
Revision 1.2: download - view: text, annotated - select for diffs
Sat May 2 21:29:02 1998 UTC (23 years, 5 months ago) by pazsan
Branches: MAIN
CVS tags: HEAD
Mega-Patch; lots of changes

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

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