Comma Format Algorithm

Updated December 22, 1996
----------------------------------------------------------------------------

Here's the shortest way I've been able to do the famous comma formatting
algorithm:

char *FormatComma(long n)
{
    static char rbuff[40];
    char t[40], *p, *r, c;
    int len;

    for (len = sprintf(p = t, "%ld", n), r = rbuff; (c = *r++ = *p++) ; )
        if (--len && c != '-' && len % 3 == 0) *r++ = ',';
    return(rbuff);
}

Here's the same thing, with a width specifier:

char *FormatComma(long n, int w)
{
    static char rbuff[40];
    char t[40], *p, *r, c;
    int len;

    for (len = sprintf(p = t, "%*ld", w, n), r = rbuff; (c = *r++ = *p++) ; )
        if (--len && c != '-' && c != ' ' && len % 3 == 0) *r++ = ',';
    return(rbuff);
}

Back to main algorithms page

----------------------------------------------------------------------------

Contents of this web page do not and are not intended to reflect the views
of CERFnet. The author of this home page is solely responsible for its
contents.
