Xref: utzoo comp.unix.questions:32378 comp.lang.c:40372 Path: utzoo!utgpu!news-server.csri.toronto.edu!rpi!zaphod.mps.ohio-state.edu!swrinde!mips!pacbell.com!ucsd!hub.ucsb.edu!fig!angst From: angst@fig.ucsb.edu (Hopelessly in love w/Donna Reed) Newsgroups: comp.unix.questions,comp.lang.c Subject: Re: How to separate numbers in three-digit groups in C Message-ID: <12192@hub.ucsb.edu> Date: 23 Jun 91 23:40:54 GMT References: <1991Jun23.174550.14820@umbc3.umbc.edu> Sender: news@hub.ucsb.edu Reply-To: angst@cs.ucsb.edu (Hopelessly in love w/Donna Reed) Followup-To: comp.lang.c Organization: Funf auf def nach oben offenen Richterskala Lines: 56 [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