jsulliva@cvbnet.UUCP (Jeff Sullivan, x4482 MS 14-13) (04/11/90)
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. */ Thanks in advance, Jeff Sullivan / Computervision/Prime \ {decvax|sun}!cvbnet!jsulliva CADDS R&D / Bedford, MA 01730 \ jsulliva@cvbnet.prime.com Jeff Sullivan / Computervision/Prime \ {decvax|linus|sun}!cvbnet!jsulliva CADDS R&D / Bedford, MA 01730 \ jsulliva@cvbnet.prime.com
jbd@dasteel.UUCP (Jonathan Dasteel) (04/14/90)
In article <193@cvbnetPrime.COM> jsulliva@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.