How can I print numbers with commas separating the thousands? What about currency formatted numbers?

Q

How can I print numbers with commas separating the thousands? What about currency formatted numbers?

✍: Guest

A

The functions in <locale.h> begin to provide some support for these operations, but there is no standard C function for doing either task. (In Standard C, the only thing printf does in response to a custom locale setting is to change its decimal-point character.)
POSIX specifies a strfmon function for formatting monetary quantities in a locale-appropriate way, and that the apostrophe flag in a numeric printf format specifier (e.g. %'d, %'f) requests comma-separated digits.
Here is a little routine for formatting comma-separated numbers, using the locale's thousands separator, if available:
#include <locale.h>
char *commaprint(unsigned long n)
{
static int comma = '\0';
static char retbuf[30];
char *p = &retbuf[sizeof(retbuf)-1];
int i = 0;

if(comma == '\0') {
struct lconv *lcp = localeconv();
if(lcp != NULL) {
if(lcp->thousands_sep != NULL &&
*lcp->thousands_sep != '\0')
comma = *lcp->thousands_sep;
else comma = ',';
}
}

*p = '\0';

do {
if(i%3 == 0 && i != 0)
*--p = comma;
*--p = '0' + n % 10;
n /= 10;
i++;
} while(n != 0);

return p;
}

(A better implementation would use the grouping field of the lconv structure, rather than assuming groups of three digits. A safer size for retbuf might be 4*(sizeof(long)*CHAR_BIT+2)/3/3+1;

2015-11-02, 1740👍, 0💬