[comp.lang.c] How to separate numbers in three-digit groups in C

angst@fig.ucsb.edu (Hopelessly in love w/Donna Reed) (06/24/91)

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

In article <1991Jun23.174550.14820@umbc3.umbc.edu> rouben@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@cs.ucsb.edu
						|    angst%cs@ucsbuxa.bitnet

dkeisen@leland.Stanford.EDU (Dave Eisen) (06/24/91)

In article <12192@hub.ucsb.edu> angst@cs.ucsb.edu (Hopelessly in love w/Donna Reed) writes:
>This function will work.  It assumes the number is contained in a string
>(which you can do by using sprintf()) --
>

No it won't. It bombs on -123 for example.

angst@fig.ucsb.edu (Hopelessly in love w/Donna Reed) (06/25/91)

In article <1991Jun24.134512.27162@leland.Stanford.EDU> dkeisen@leland.Stanford.EDU (Dave Eisen) writes:
>In article <12192@hub.ucsb.edu> angst@cs.ucsb.edu (Hopelessly in love w/Donna Reed) writes:
>>This function will work.  It assumes the number is contained in a string
>>(which you can do by using sprintf()) --
>>
>
>No it won't. It bombs on -123 for example.

True, my solution doesn't work for negative numbers.  

Add the following as the first line of the function:

	if (s && *s == '-') {
	    putchar ('-');
	    s++;
	}

-d

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