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?
The character used as the thousands separatorIn the United States, this character is a comma (,). In Germany, it is a period (.). Thus one thousand and twenty-five is displayed as 1,025 in the United States and 1.025 in Germany. In Sweden, the thousands separator is a space.
Using the modern f-strings is, in my opinion, the most Pythonic solution to add commas as thousand-separators for all Python versions above 3.6: f'{1000000:,}' . The inner part within the curly brackets :, says to format the number and use commas as thousand separators.
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
.
localedata/locales/
directory from an existing file en_US
a new file en_AT
.thousands_sep
to thousands_sep "<U0027>"
or whatever character you want to have as the thousands separator.en_US
to en_AT
.localedata/SUPPORTED
the line: en_AT.UTF-8/UTF-8 \
.make localedata/install-locales
.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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With