Set thousands separator for C printf

c, locale, printf

Solution

Here is a very simple solution which works on each linux distribution and does not need - as my 1st answer - a `glibc` hack:

All these steps must be performed in the origin `glibc` directory - NOT in the build directory - after you built the `glibc` version using a separate build directory as suggested by this instructions.

My new `locale` file is called `en_AT`.

- Create in the `localedata/locales/` directory from an existing file `en_US` a new file `en_AT` .

- Change all entries for `thousands_sep` to `thousands_sep "<U0027>"` or whatever character you want to have as the thousands separator.

- Change inside of the new file all occurrences of `en_US` to `en_AT`.

- Add to the file `localedata/SUPPORTED` the line: `en_AT.UTF-8/UTF-8 \`.

- Run in the build directory `make localedata/install-locales`.

- The new `locale` will be then automatically added to the system and is instantly accessible for the program.

In the C/C++ program you switch to the new thousands separator character with:

`setlocale( LC_ALL, "en_AT.UTF-8" );`

using it with `printf( "%'d", 1000000 );` which produces this output

1'000'000

Remark: When you need in the program different localizations which are determinated while the runtime you can use this example from the `man` pages where you load the requested `locale` and just replace the `LC_NUMERIC` settings from `en_AT`.

Problem

I have this C code: ``` locale_t myLocale = newlocale(LC_NUMERIC_MASK, "en_US", (locale_t) 0); uselocale(myLocale); ptrLocale = localeconv(); ptrLocale->thousands_sep = (char *) "'"; int i1 = snprintf( s1, sizeof(s1), "%'d", 123456789); ``` The output in `s1` is `123,456,789`. Even I set `->thousands_sep` to `'` it is ignored. Is there a way to set any character as the thousands separator?

Original source

Related problems