Digit grouping in C's printf

Gnubie picture Gnubie · May 15, 2012 · Viewed 10k times · Source

I wish to output large numbers with thousand-separators (commas or spaces) — basically the same as in How to display numeric in 3 digit grouping but using printf in C (GNU, 99).

If printf does not support digit grouping natively, how can I achieve this with something like printf("%s", group_digits(number))?

It must support negative integers and preferably floats, too.

Answer

pmg picture pmg · May 15, 2012

If you can use POSIX printf, try

#include <locale.h>
setlocale(LC_ALL, ""); /* use user selected locale */
printf("%'d", 1000000);