1 #include <math.h> 2 #include <stdlib.h> 3 double pow10(int); 4 #define NDIG 18 5 #define NFTOA (NDIG+4) 6 /* 7 * convert floating to ascii. ftoa returns an integer e such that 8 * f=g*10**e, with .1<=|g|<1 (e=0 when g==0) and puts an ascii 9 * representation of g in the buffer pointed to by bp. bp[0] will 10 * be '+' or '-', and bp[1] to bp[NFTOA-2] 11 * will be appropriate digits of g. bp[NFTOA-1] will be '\0' 12 */ 13 int ftoa(double f, char *bp){ 14 int e, e1, e2, i; 15 double digit, g, p; 16 if(f>=0) *bp++='+'; 17 else{ 18 f=-f; 19 *bp++='-'; 20 } 21 /* find e such that f==0 or 1<=f*pow10(e)<10, and set f=f*pow10(e) */ 22 if(f==0.) e=1; 23 else{ 24 frexp(f, &e); 25 e=-e*30103/100000; 26 /* split in 2 pieces to guard against overflow in extreme cases */ 27 e1=e/2; 28 e2=e-e1; 29 p=f*pow10(e2); 30 while((g=p*pow10(e1))<1.) e1++; 31 while((g=p*pow10(e1))>=10.) --e1; 32 e=e1+e2; 33 f=g; 34 } 35 for(i=0;i!=NDIG;i++){ 36 f=modf(f, &digit)*10.; 37 *bp++=digit+'0'; 38 } 39 *bp='\0'; 40 return 1-e; 41 } 42