commas for numbers like 400,000 in C

Hi, I was wondering if there was a way to make commas appear every three digits in C, to make the output easier to read. thanks…

Okay, so I read it, and maybe I just don’t get it, but I don’t see any mention of commas? any help?

Whups, sorry. Wrong link.
Try this

that explains why the other didn’t seem related! however, I still don’t get it, from this link, I can’t tell what part of his code is used for putting the commas, not trying to be dense but…

Er, yeah, that code was rather dense…

Unfortunately, in C there is no convenient way to add commas, so you need to roll your own. Try:

/* function
     Add commas to a string representation of an integer number.
     s  The string to convert. It is presumed that the string has sufficient space for the result.
void commify( char *s ) {
  int count3;
  int oldlen = strlen( s );
  int newlen = oldlen +((oldlen -1) /3);
  s[ newlen-- ] = 0;
  for (count3 = 0, oldlen--; oldlen > 0; oldlen--, newlen--, count3++) {
    if (count3 > 2) {
      count3 = 0;
      s[ newlen-- ] = ',';
    s[ newlen ] = s[ oldlen ];

BTW, I just hacked this code off the top of my head (so it might not work… post again if it doesn’t and you can’t fix it). It can be modified to handle rational numbers as well…

To use it, use sprintf() to get your number into a string, then use commify() to add the commas, then you can printf() the string with the appropriate justifications.

Hope this helps.