Programming Search⌘K

Conceptcore

Locale-aware formatting

Also called locale-aware formatting, localized formatting, locale formatting, number localization, l10n of numbers, culture-specific formatting, CultureInfo, Intl.NumberFormat, setlocale, LC_NUMERIC, CLDR, ICU, decimal separator, digit grouping, thousands separator.

Locale-aware formatting shows a number, a price or a date with the symbols and the digit groups of a language and region, so 1234.5 is 1,234.5 in English and 1.234,5 in German.

Applies to
core-languages

Idea

People write numbers in different ways. "A decimal separator is a symbol that separates the integer part from the fractional part of a number written in decimal form. Different countries officially designate different symbols for use as the separator"1. The number 1234567.891 is 1,234,567.891 in the United States, 1.234.567,891 in Germany and 12,34,567.891 in India.

A locale is a set of rules for a language and a region, such as en-US, de-DE or hi-IN. A locale-aware format function takes a value and a locale, and it uses the symbols and the groups of that locale:

const n = 1234567.891;
for (const loc of ["en-US", "de-DE", "en-IN", "ja-JP"]) {
  console.log(loc.padEnd(6), new Intl.NumberFormat(loc).format(n));
}
Output
en-US  1,234,567.891
de-DE  1.234.567,891
en-IN  12,34,567.891
ja-JP  1,234,567.891

The value is the same in each line. Only the text is different.

How it works

The locale data. A program does not know the rules of each country. It reads them from a database. The main database today is CLDR: "CLDR (Common Locale Data & Rules) supplies key information and structures critical for programs and operating systems around the world to ensure that they feel natural, no matter which language users speak or where they live"2. It has data for "Over 100 languages"2: the decimal and group symbols, the digit groups, the currency symbols, the names of months and days, and the date patterns. The ICU libraries, the JavaScript Intl API, Java and .NET use the CLDR data. Unix systems have a second database, the POSIX locales, which C and Python use.

What a locale changes in a number.

  • The decimal separator: . in English, , in German and French.
  • The group separator: , in English, . in German, a space in French and ' in Swiss German.
  • The group sizes. Most locales use groups of 3. "There may be two different grouping sizes: The primary grouping size used for the least significant integer group, and the secondary grouping size used for more significant groups; these are not the same in all locales"3. India uses 3 for the first group and 2 for the others.
  • The digits. Some locales use other digits, for example the Arabic-Indic digits in Egypt.
  • The currency. The symbol, its place before or after the number, and the number of decimals: the euro has 2, and the Japanese yen has 04.

Two ways to give the locale.

  • A global locale. C has one locale for the program. At startup, a C program runs the equivalent of setlocale(LC_ALL, "C") before any user code5, so it uses the neutral rules until it calls setlocale. The C function localeconv returns a struct with decimal_point, thousands_sep and grouping6. Python's module locale uses the same model.
  • A locale argument. Java, .NET and JavaScript take the locale as an argument of each call, or from an object: String.format(Locale.GERMANY, ...), x.ToString("N2", culture) and new Intl.NumberFormat("de-DE"). This is clearer, because the result of a call depends only on its arguments.

The neutral locale. Each system has one locale that never changes: the "C" locale in C and Python, Locale.ROOT in Java and CultureInfo.InvariantCulture in .NET. A program uses it for text that another program reads.

In languages

LanguageVerdictNote
PythonStandard library
C++Standard library
JavaStandard library
CStandard library
C#Standard library
JavaScriptStandard library
TypeScriptStandard libraryTypeScript uses the JavaScript object Intl, with Intl.NumberFormat, Intl.DateTimeFormat and toLocaleString, and has types for their options. No example file exists.
GoLibrary
RustLibrary
KotlinStandard libraryKotlin uses the Java classes, such as String.format(Locale.GERMANY, "%,.2f", x) and NumberFormat.getInstance(locale). No example file exists because kotlinc is not installed.
SQLIdiomStandard SQL has no locale formatting. PostgreSQL and Oracle have to_char with the patterns G and D for the group and decimal symbols of the session locale, and SQL Server has FORMAT with a culture argument. No example file exists.
BashNativeThe Bash builtin printf takes the POSIX flag ' in %'d and uses the locale in LC_NUMERIC or LC_ALL, such as LC_NUMERIC=en_US.UTF-8 printf "%'d" 1234567. No example file exists.
PowerShellStandard libraryPowerShell uses the .NET class CultureInfo. The operator -f and the method ToString use the current culture, and a program can pass a culture, such as $x.ToString("N2", [cultureinfo]"de-DE"). No example file exists because pwsh is not installed.
HTMLDoes not applyThe attribute lang names the language of the text, but HTML does not format numbers or dates.
CSSDoes not applyCSS does not format numbers or dates.
Regular expressionsDoes not applyA regular expression matches text and does not format values.
Language Verdict Mechanism
Python stdlib the module locale with setlocale, format_string and the format type n; the library Babel for CLDR data
JavaScript stdlib Intl.NumberFormat, Intl.DateTimeFormat and toLocaleString, with the CLDR data
TypeScript stdlib as in JavaScript
Java stdlib a Locale argument for String.format, and NumberFormat, DecimalFormat and DateTimeFormatter
Kotlin stdlib the Java classes, through String.format(locale, ...)
C# stdlib CultureInfo and NumberFormatInfo, through ToString("N2", culture) and string.Format(culture, ...)
Go library no locale in the package fmt; the module golang.org/x/text/message adds it
Rust library no locale in std::fmt; crates such as num-format and icu add it
C stdlib setlocale, localeconv, strfmon and the POSIX flag ' in printf
C++ stdlib std::locale, the option L of std::format and the facets of <locale>
Bash native the builtin printf with the flag ', after LC_NUMERIC is set
PowerShell stdlib the .NET CultureInfo; -f and ToString use the current culture
SQL idiom to_char with the patterns G and D in PostgreSQL and Oracle, and FORMAT with a culture in SQL Server
Regex n/a patterns match text and do not format values
HTML n/a the attribute lang names the language of the text, but HTML does not format numbers
CSS n/a CSS does not format numbers

Python. The module locale sets a global locale. "Initially, when a program is started, the locale is the C locale, no matter what the user’s preferred locale is"7. Only some functions use it: "The functions format_string(), atoi(), atof() and str() of the locale module are affected by that category. All other numeric formatting operations are not affected"7. The format type n is the exception: "This is the same as 'd', except that it uses the current locale setting to insert the appropriate digit group separators"8. The option , always gives commas.

C++. std::format ignores the locale unless the specifier has L. "For integral types, the locale-specific form inserts the appropriate digit group separator characters according to the context's locale"9.

Java and C#. The methods take a locale. Java's documentation shows formatter.format(Locale.FRANCE, "e = %+10.4f", Math.E), which gives e = +2,718310. In .NET, the format N gives "Integral and decimal digits, group separators, and a decimal separator with optional negative sign"11, and "The result string is affected by the formatting information of the current NumberFormatInfo object"11. Without an argument, both use the locale of the user, so the same program can print different text on two computers.

Go and Rust. The standard formatting has no locale. "The format functions provided by Rust’s standard library do not have any concept of locale and will produce the same results on all systems regardless of user configuration"12. A program that must show local numbers uses a library.

PythonGitHub
import locale

n = 1234567
x = 1234567.891

print(locale.setlocale(locale.LC_NUMERIC))
print(f"{n:n}", f"{n:,}", locale.format_string("%.2f", x, grouping=True))

locale.setlocale(locale.LC_NUMERIC, "en_US.UTF-8")
conv = locale.localeconv()
print(repr(conv["decimal_point"]), repr(conv["thousands_sep"]), conv["grouping"])
print(f"{n:n}", locale.format_string("%.2f", x, grouping=True))
print(locale.atof("1,234.5"))

locale.setlocale(locale.LC_NUMERIC, "C")
print(f"{n:n}", f"{x:.2f}")
Output
C
1234567 1,234,567 1234567.89
'.' ',' [3, 0]
1,234,567 1,234,567.89
1234.5
1234567 1234567.89
  • Verdict: stdlib. The module locale sets a global locale from the POSIX database, and only format_string, atof, atoi, str and the format type n use it. The option , always gives commas. The program needs the locale en_US.UTF-8 on the system. For the CLDR data of many locales without a global state, a program uses the library Babel.
#include <format>
#include <iostream>
#include <locale>

int main() {
    long n = 1234567;
    double x = 1234567.891;
    std::cout << std::format("{} {:L} {:.2Lf}\n", n, n, x);

    std::locale us("en_US.UTF-8");
    std::cout << std::format(us, "{} {:L} {:.2Lf}\n", n, n, x);

    std::locale::global(us);
    std::cout << std::format("{} {:L}\n", n, n);
    std::cout << n << '\n';
    std::cout.imbue(us);
    std::cout << n << '\n';
}
Output
1234567 1234567 1234567.89
1234567 1,234,567 1,234,567.89
1234567 1,234,567
1234567
1,234,567
  • Verdict: stdlib. std::format ignores the locale unless a specifier has the option L. Then it uses the locale argument, or the global locale. A stream such as std::cout keeps the locale it had when it was made, so a change of the global locale does not change it until imbue. The constructor std::locale("en_US.UTF-8") throws std::runtime_error if the system does not have the locale.
JavaGitHub
import java.text.NumberFormat;
import java.util.Locale;

public class Main {
    public static void main(String[] args) {
        double x = 1234567.891;
        System.out.println(String.format(Locale.US, "%,.2f", x));
        System.out.println(String.format(Locale.GERMANY, "%,.2f", x));
        System.out.println(String.format(Locale.ROOT, "%.2f", x));
        System.out.println(String.format(Locale.FRANCE, "e = %+10.4f", Math.E));

        String fr = String.format(Locale.FRANCE, "%,.0f", x);
        System.out.printf("U+%04X%n", (int) fr.charAt(1));

        NumberFormat usd = NumberFormat.getCurrencyInstance(Locale.US);
        System.out.println(usd.format(x));
        NumberFormat de = NumberFormat.getInstance(Locale.GERMANY);
        System.out.println(de.format(x));
    }
}
Output
1,234,567.89
1.234.567,89
1234567.89
e =    +2,7183
U+202F
$1,234,567.89
1.234.567,891
  • Verdict: stdlib. String.format, Formatter and NumberFormat take a Locale, and the flag , asks for the group separator of that locale. Without a locale argument, String.format uses the default locale of the computer, so a program passes Locale.ROOT for machine text. Java reads the CLDR data by default.
#include <limits.h>
#include <locale.h>
#include <stdio.h>

static void show(void) {
    struct lconv *lc = localeconv();
    printf("decimal_point='%s' thousands_sep='%s' grouping=", lc->decimal_point, lc->thousands_sep);
    for (const char *g = lc->grouping; *g != 0 && *g != CHAR_MAX; g++) {
        printf("%s%d", g == lc->grouping ? "" : ",", *g);
    }
    printf("\n%'d %'.2f\n", 1234567, 1234567.891);
}

int main(void) {
    printf("%s\n", setlocale(LC_NUMERIC, NULL));
    show();
    if (setlocale(LC_NUMERIC, "en_US.UTF-8") == NULL) {
        printf("the locale en_US.UTF-8 is not installed\n");
        return 1;
    }
    printf("%s\n", setlocale(LC_NUMERIC, NULL));
    show();
    setlocale(LC_NUMERIC, "C");
    printf("%.2f\n", 1234567.891);
    return 0;
}
Output
C
decimal_point='.' thousands_sep='' grouping=
1234567 1234567.89
en_US.UTF-8
decimal_point='.' thousands_sep=',' grouping=3
1,234,567 1,234,567.89
1234567.89
  • Verdict: stdlib. setlocale sets one global locale for the program, and localeconv returns its symbols and group sizes. The group sizes 3 mean groups of 3, and the last size repeats. The program starts in the locale "C", so printf has no group separator until the program calls setlocale. The flag ' in %'d comes from POSIX, not from ISO C, and setlocale fails if the system does not have the locale.
using System;
using System.Globalization;

double x = 1234567.891;
foreach (var name in new[] { "en-US", "de-DE", "en-IN", "de-CH" })
{
    var c = CultureInfo.GetCultureInfo(name);
    Console.WriteLine($"{name} {x.ToString("N2", c)}");
}

var inv = CultureInfo.InvariantCulture;
Console.WriteLine(x.ToString("N2", inv) + " " + x.ToString(inv));
Console.WriteLine(string.Format(CultureInfo.GetCultureInfo("de-DE"), "{0:F1}", 2.5));
var nf = CultureInfo.GetCultureInfo("en-IN").NumberFormat;
Console.WriteLine(string.Join(",", nf.NumberGroupSizes));
Console.WriteLine(double.Parse("1.234,5", CultureInfo.GetCultureInfo("de-DE")).ToString(inv));
Output
en-US 1,234,567.89
de-DE 1.234.567,89
en-IN 12,34,567.89
de-CH 1’234’567.89
1,234,567.89 1234567.891
2,5
3,2
1234.5
  • Verdict: stdlib. A CultureInfo holds a NumberFormatInfo with the separators and the group sizes, and ToString, string.Format and double.Parse take it as an argument. Without one, they use the current culture of the thread. CultureInfo.InvariantCulture is the neutral culture for machine text. On Linux, .NET reads the culture data from ICU.
JavaScriptGitHub
const n = 1234567.891;
for (const loc of ["en-US", "de-DE", "fr-FR", "en-IN", "ar-EG"]) {
  const s = new Intl.NumberFormat(loc).format(n);
  const odd = [...s].filter((c) => c > "~").map((c) => "U+" + c.codePointAt(0).toString(16).toUpperCase().padStart(4, "0"));
  console.log(loc, odd.length ? [...new Set(odd)].join(" ") : s);
}

const usd = new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" });
const jpy = new Intl.NumberFormat("ja-JP", { style: "currency", currency: "JPY" });
console.log(usd.format(n), jpy.format(n).replace("¥", "Yen "));

const d = new Date(Date.UTC(2026, 0, 2));
for (const loc of ["en-US", "en-GB", "de-DE"]) {
  console.log(loc, d.toLocaleDateString(loc, { timeZone: "UTC" }));
}
console.log((0.5).toLocaleString("en-US", { style: "percent" }), String(n));
Output
en-US 1,234,567.891
de-DE 1.234.567,891
fr-FR U+202F
en-IN 12,34,567.891
ar-EG U+0661 U+066C U+0662 U+0663 U+0664 U+0665 U+0666 U+0667 U+066B U+0668 U+0669
$1,234,567.89 Yen 1,234,568
en-US 1/2/2026
en-GB 02/01/2026
de-DE 2.1.2026
50% 1234567.891
  • Verdict: stdlib. Intl.NumberFormat and Intl.DateTimeFormat use the CLDR data of the runtime, and toLocaleString is a short form. The French group separator is U+202F, a narrow no-break space, and Arabic in Egypt uses Arabic-Indic digits. String(n) never uses a locale, so it is safe for machine text.
package main

import (
	"fmt"
	"strconv"
	"strings"
)

type locale struct {
	name, group, decimal string
}

func format(x float64, digits int, loc locale) string {
	text := strconv.FormatFloat(x, 'f', digits, 64)
	sign := ""
	if strings.HasPrefix(text, "-") {
		sign, text = "-", text[1:]
	}
	whole, frac, _ := strings.Cut(text, ".")
	var b strings.Builder
	for i := range len(whole) {
		if i > 0 && (len(whole)-i)%3 == 0 {
			b.WriteString(loc.group)
		}
		b.WriteByte(whole[i])
	}
	if frac != "" {
		b.WriteString(loc.decimal + frac)
	}
	return sign + b.String()
}

func main() {
	x := 1234567.891
	for _, loc := range []locale{{"en-US", ",", "."}, {"de-DE", ".", ","}, {"it-CH", "'", "."}} {
		fmt.Println(loc.name, format(x, 2, loc), format(-1234.5, 1, loc))
	}
	fmt.Printf("%.2f %v\n", x, x)
}
Output
en-US 1,234,567.89 -1,234.5
de-DE 1.234.567,89 -1.234,5
it-CH 1'234'567.89 -1'234.5
1234567.89 1.234567891e+06
  • Verdict: library. The package fmt has no locale, so %.2f gives the same text on each computer. The module golang.org/x/text/message adds a Printer for a language tag with the CLDR data. Without it, a program puts in the symbols itself, as here, and it must know the group sizes of each locale.
RustGitHub
struct Locale {
    name: &'static str,
    group: &'static str,
    decimal: &'static str,
}

fn format(x: f64, digits: usize, loc: &Locale) -> String {
    let text = format!("{:.*}", digits, x.abs());
    let (whole, frac) = text.split_once('.').unwrap_or((text.as_str(), ""));
    let mut out = String::new();
    for (i, c) in whole.chars().enumerate() {
        if i > 0 && (whole.len() - i) % 3 == 0 {
            out.push_str(loc.group);
        }
        out.push(c);
    }
    if !frac.is_empty() {
        out.push_str(loc.decimal);
        out.push_str(frac);
    }
    if x < 0.0 { format!("-{out}") } else { out }
}

fn main() {
    let x = 1234567.891;
    let locales = [
        Locale { name: "en-US", group: ",", decimal: "." },
        Locale { name: "de-DE", group: ".", decimal: "," },
        Locale { name: "it-CH", group: "'", decimal: "." },
    ];
    for loc in &locales {
        println!("{} {} {}", loc.name, format(x, 2, loc), format(-1234.5, 1, loc));
    }
    println!("{x:.2} {x}");
}
Output
en-US 1,234,567.89 -1,234.5
de-DE 1.234.567,89 -1.234,5
it-CH 1'234'567.89 -1'234.5
1234567.89 1234567.891
  • Verdict: library. std::fmt has no concept of a locale, and the same program gives the same text on each system. The crate num-format adds the group separators of many locales, and the icu crates of the ICU4X project add the full CLDR data. Without them, a program puts in the symbols itself, as here.
  • Dates and times. A locale also gives the order of day, month and year, the names of the months, and the 12-hour or 24-hour clock. Intl.DateTimeFormat, DateTimeFormatter.ofLocalizedDate and the format d in .NET use it.
  • Plural forms and messages. A full translation also needs plural rules and message formats, such as ICU MessageFormat. This is internationalization, and the numbers are one part of it.
  • Parsing. The reverse operation reads a number from local text: locale.atof, NumberFormat.parse and double.Parse(s, culture).
  • Grouping without a locale. {:,} in Python and N0 with the invariant culture give fixed commas. See Format a number with separators.

Pitfalls

  • Machine text with a user locale. A number in a log, a CSV file, JSON or an SQL query must use the neutral locale. If a program writes 3,5 on a German computer, a reader that expects 3.5 fails, or reads a wrong value. Pass the neutral locale explicitly: Locale.ROOT, CultureInfo.InvariantCulture or no setlocale call.
  • Parsing with the wrong locale. In German, . is the group separator, so a parser can read 1.5 as 15:

This code runs but gives a wrong answer on purpose.

using System;
using System.Globalization;

var de = CultureInfo.GetCultureInfo("de-DE");
Console.WriteLine(double.Parse("1.5", de));
Console.WriteLine(double.Parse("1.5", CultureInfo.InvariantCulture));
Output
15
1.5
  • A global locale is shared. setlocale changes the locale of the whole program. Python warns: "It is generally a bad idea to call setlocale() in some library routine, since as a side effect it affects the entire program"7. Other threads see the change too.
  • The locale is not installed. On Linux, setlocale(LC_ALL, "de_DE.UTF-8") fails if the system does not have that locale. Check the return value. CLDR-based APIs carry their own data, but a small build can omit it.
  • Non-ASCII separators. In the current CLDR data, the French group separator is a narrow no-break space, U+202F, not a normal space. A test that compares with "1 234,5" fails, and the CLDR data changes between versions. Do not compare localized text in tests, or build the expected text from the same API.
  • Special values. Java says of NaN and infinity: "These values are not localized"10. Other APIs give NaN, ∞ or a local word.

Cost

A locale-aware call is slower than a plain format, because it looks up the locale data and applies more rules. Creating a formatter, such as Intl.NumberFormat or DecimalFormat, parses the locale data, so a program creates it once and reuses it in a loop. The CLDR data is large: a full ICU data file has tens of megabytes, so some runtimes ship a smaller set.

History

The locale model of C came with the first C standard, which defined setlocale, localeconv and the categories LC_NUMERIC, LC_MONETARY and LC_TIME5. The decimal symbol was a question for standards bodies too: in 2003, the 22nd General Conference on Weights and Measures declared "The symbol for the decimal marker shall be either the point on the line or the comma on the line"1. The Unicode Consortium started CLDR to give all systems the same locale data, and the JavaScript Intl object put it in the browser: Intl.NumberFormat has been "available across browsers since September 2017"4.

References

  1. Decimal separator, Wikipedia, Introduction; Digit grouping; Current international standards
  2. Unicode CLDR Project, What is CLDR
  3. Unicode Technical Standard, Number Patterns; Grouping
  4. Intl.NumberFormat, MDN Web Docs, Description; Examples
  5. setlocale, C reference, cppreference.com, Notes
  6. lconv, C reference, cppreference.com, Member objects
  7. locale, Internationalization services, Python documentation, Background, details, hints, tips and caveats; LC_NUMERIC
  8. string, Common string operations, Python documentation, Format Specification Mini-Language
  9. Standard format specification, C++ reference, cppreference.com, L (locale-specific formatting)
  10. Class Formatter, Java SE 25 API, Localization
  11. Standard numeric format strings, .NET documentation, Number format specifier (N); NumberFormatInfo properties
  12. Module std::fmt, The Rust Standard Library, Localization

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/843W4A/text.yaml