Formatting large numbers (999,999,999)

Jonathan Dasteel jbd at dasteel.UUCP
Sat Apr 14 04:27:16 AEST 1990


In article <193 at cvbnetPrime.COM> jsulliva at cvbnet.UUCP (Jeff Sullivan, x4482 MS 14-13) writes:

	  Does anyone have a nice way to print out numbers with
	  the correct placement of commas?

	  For example:
	   2,147,483,648
	  instead of
	   2147483648	/* using printf("%10.0f",x); */
			   /*   where x is a double.    */

Try this (for integer):

		  char *intAddCommas( int i ) {
			  static char buf[64];
			  buf[31] = 0;
			  int len = 30;
			  int mod = 0;
			  if( !i ) {
				  strcpy( buf, "0" );
				  return buf;
			  }
			  while( i ) {
				  buf[len--] = (i % 10) + '0';
				  i /= 10;
				  mod++;
				  if( i && !(mod%3)) {
					  buf[len--] = ',';
				  }
			  }
			  return &buf[len+1];
		  }

or this (for float, s is formatted by sprintf(s,"%.*f",decimal,number)):

			 char *numAddCommas( char *s, int decimal ) {
				 static char buf[64];
				 buf[31] = 0;
				 int len = 30;
				 int mod = 0;
				 int sl = strlen( s) -1;
				 if( decimal )
					 decimal++;
				 while( decimal-- )
					 buf[len--] = s[sl--];
				 while( sl >= 0 ) {
					 buf[len--] = s[sl--];
					 mod++;
					 if( (sl>=0) && !(mod%3)) {
						 buf[len--] = ',';
					 }
				 }
				 return &buf[len+1];
			 }

Hope this helps.



More information about the Comp.lang.c mailing list