[comp.lang.c] printing double in n character field

jamshid@emx.utexas.edu (Jamshid Afshar) (01/16/91)

I am trying to sprintf a double into a character string so the
string can be edited by the user.  The problem is I want the string to
always be a set length.  I thought I had finally come up with a
solution (see below) using significant digits, but I forgot about
cases where zeroes immediately follow the decimal point (those zeroes
are not sig. digs).  These are examples of what I would like (width==5):

I have this double value   I want this string
	12345.6 		|12345|
	12.4			| 12.4|
	1234.5			| 1235|
	1.00004			|    1|
	0.0004			|    0|
	0.00453			|0.005|

The following doesn't work for the last two examples.

// pre: s points to 'width' characters and d can be displayed in width chars
// post: s is a valid numeric string and strlen(s)==width
void numtoa(char *s, double d, int width)
{
   int sigdigs = max_num_len(ceil(d));
   if (sigdigs<=width-2) {    // if at least one decimal place will fit
      if (d<1) sigdigs = width-2;   // 1 for decimal point, 1 for zero
      else sigdigs = width-1;       // subtract 1 for decimal point
      }
   sprintf(s, "%*.*lg", width, sigdigs, d);
}

int max_num_len(unsigned long number)
{
   if (number<10) return 1;
   else if (number < 100) return 2;
   else if (number < 1000) return 3;
// ... you get the idea
}

I'm sure I'm not the first to need something like this.  I would fix
mine, but I'm hoping there is a more elegant solution.  I'll post a
summary.

Thanks, Jamshid Afshar
jamshid@emx.utexas.edu