Alex Rivera | Logout

How to format a number using comma as thousands separator in C?

Asked 2009-09-19T23:38:19.433
117

In C, how can I format a large number from e.g. 1123456789 to 1,123,456,789?

I tried using printf("%'10d\n", 1123456789), but that doesn't work.

Could you advise anything? The simpler the solution the better.

Edit
Report

1 Answer

14

Here's a very simple implementation. This function contains no error checking, buffer sizes must be verified by the caller. It also does not work for negative numbers. Such improvements are left as an exercise for the reader.

void format_commas(int n, char *out)
{
    int c;
    char buf[20];
    char *p;

    sprintf(buf, "%d", n);
    c = 2 - strlen(buf) % 3;
    for (p = buf; *p != 0; p++) {
       *out++ = *p;
       if (c == 1) {
           *out++ = ',';
       }
       c = (c + 1) % 3;
    }
    *--out = 0;
}
answered 2009-09-19T23:56:21.330

Your Answer