C Locales

Definition
What Is a Locale in C?
A locale is a package of cultural conventions: how numbers look, how dates are written, how text is compared, and related rules. The <locale.h> header lets a beginner change those rules with setlocale() and inspect numeric formatting with localeconv().
Programs start in the portable C locale. That keeps behavior predictable. If you want the user’s environment settings, call setlocale(LC_ALL, "") and check for NULL.
Key idea.
Use the C locale for portable parsing and printing. Switch only when you truly need local conventions.
Macros
Common Locale Categories
| Macro | Typical meaning |
|---|---|
LC_ALL | Every category at once. |
LC_NUMERIC | Number formatting rules. |
LC_TIME | Date and time formatting. |
LC_CTYPE | Character classification and case. |
LC_COLLATE | String comparison / sorting rules. |
LC_MONETARY | Currency formatting rules. |
Pattern
The Set and Read Pattern
- Decide the locale. Prefer
"C"for portable work, or""for the environment. - Call setlocale(). Check for
NULLbefore continuing. - Read fields if needed. Use
localeconv()fordecimal_pointand related values. - Copy what you keep. Static
lconvdata can change after another locale switch.
Example
Starter: Set C Locale and Read decimal_point
C
#include <stdio.h>
#include <locale.h>
int main(void) {
if (setlocale(LC_ALL, "C") == NULL) {
printf("setlocale failed\n");
return 1;
}
struct lconv *lc = localeconv();
printf("locale = %s\n", setlocale(LC_ALL, NULL));
printf("decimal_point = \"%s\"\n", lc->decimal_point);
return 0;
} How It Works
- Set the C locale.
setlocale(LC_ALL, "C")selects portable rules. - Check for failure. A NULL result means the request did not apply.
- Read formatting fields.
localeconv()returns the activelconvrecord. - Print decimal_point. In the C locale this is normally a dot.
Next steps
Open the Function Guides
Frequently Asked Questions
A locale is a set of cultural conventions for numbers, dates, collation, and related behavior. locale.h lets a program set or query those rules.
The portable default. Select it with setlocale(LC_ALL, "C"). Programs start there.
setlocale(category, "") asks for the environment locale from LANG / LC_*.
Learn setlocale() to change or query, then localeconv() to read formatting fields.
No. Names and available locales depend on the operating system. Always check for NULL.
Browse locale.h functions
Open setlocale() and localeconv() with full examples.
8 people found this page helpful
