Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set thousands separator for C printf

Tags:

c

printf

locale

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?

like image 403
Peter VARGA Avatar asked Feb 26 '15 14:02

Peter VARGA


People also ask

How do you format a 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.

How do you add a thousand separator in Python?

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.


Video Answer


1 Answers

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.

  1. Create in the localedata/locales/ directory from an existing file en_US a new file en_AT .
  2. Change all entries for thousands_sep to thousands_sep "<U0027>" or whatever character you want to have as the thousands separator.
  3. Change inside of the new file all occurrences of en_US to en_AT.
  4. Add to the file localedata/SUPPORTED the line: en_AT.UTF-8/UTF-8 \.
  5. Run in the build directory make localedata/install-locales.
  6. 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.

like image 89
Peter VARGA Avatar answered Oct 22 '22 01:10

Peter VARGA