How to separate numbers in three-digit groups in C

Hopelessly in love w/Donna Reed angst at fig.ucsb.edu
Mon Jun 24 09:40:54 AEST 1991


[This should have been posted to comp.lang.c; I have directed followups there.]

In article <1991Jun23.174550.14820 at umbc3.umbc.edu> rouben at math16.math.umbc.edu (Rouben Rostamian) writes:
>
>I need help with printing numbers (floating or integer) in C.  I would like
>to display the numbers in three-digit comma-separated format.  For instance,
>the integer 12345678 should be printed as 12,345,678.  The floating point
>number 1234.56789 may be printed as 1,234.5678 or as 1,234.567,8.
>I wish the printf function had an option for such formatting, but
>as far as I know, it doesn't.  

This function will work.  It assumes the number is contained in a string
(which you can do by using sprintf()) --

    void commas (char *s)
    {
	char *p = index (s, '.');
	int count;

	if (p)
	    *p = '\0';			/* ignore fractional part for now */

	count = strlen (s);		

	while (count-- > 0) {
	    putchar (*s++);
	    if (count > 0 && count % 3 == 0)
		 putchar (',');
	}
	if (p)
	    printf (".%s", p+1);		/* print out fractional part */
    }

Here's the output of the short program I wrote to test this:

Script started on Sun Jun 23 16:37:37 1991
manray% a.out
enter string: 123
123
enter string: 1234
1,234
enter string: 123456
123,456
enter string: 12345678901
12,345,678,901
enter string: 34.2732
34.2732
enter string: 35276.28321
35,276.28321
enter string: ^C
manray% exit
script done on Sun Jun 23 16:38:03 1991

"Let the fools have their tartar sauce."	|          Dave Stein
  		        - Mr. Burns		|       angst at cs.ucsb.edu
						|    angst%cs at ucsbuxa.bitnet



More information about the Comp.unix.questions mailing list