Skip to content

Locales & Formatting

This chapter writes numbers, prices, dates and lists the way a reader’s language writes them, and reads back what they type. A locale names one way of writing: a language, and sometimes a region, such as English as written in the United States. An American writes 1,299.50, a German 1.299,50.

Nomi never guesses the locale. Every function whose result depends on one takes the locale as an argument. The rules for each locale come from CLDR, a shared collection of locale data kept by the Unicode project.

The examples come from a shop’s order page: what the items cost, when they ship, and who else is looking at them. The next chapter, Translating Text, translates the page’s sentences.

A Locale is written as a short code called a language tag, in a typed literal: Locale"en-US" is English as written in the United States, Locale"de" is German, and Locale"pt-BR" is Portuguese as written in Brazil. The language comes first, then the region. Locale is in the prelude, so it needs no import.

Int.format, Float.format and Decimal.format write a number the way a reader of a locale expects. Float.format_percent and Decimal.format_percent write a fraction as a percentage, so 0.15 becomes 15%. Use Decimal for amounts that must stay exact. A price in a currency is a Money, shown below.

import std::io

fn main()
    sold = 1234567
    price = 1299.50d
    discount = 0.15d

    [
        Locale"en-US",
        Locale"de",
        Locale"fr",
        Locale"hi",
        Locale"ar-EG",
        Locale"ar-EG-u-nu-latn",
    ]
    |> Iter.each(fn locale ->
        count = Int.format(sold, locale)
        amount = Decimal.format(price, locale)
        off = Decimal.format_percent(discount, locale)
        io.print("${locale}: ${count} sold, ${amount}, ${off} off")
    end)
end

German swaps the comma and the dot. French separates thousands with a thin space that never breaks across lines. Hindi groups digits in twos after the first three, so 1,234,567 is 12,34,567. Egyptian Arabic uses Arabic digits. Adding -u-nu-latn to a locale makes it use the digits 0 to 9 and the separators that go with them.

Putting a number in a string, as in "${sold}", always gives 1234567. That text often ends up in web addresses, headers or CSV files, which a program reads, so it must not change from reader to reader.

Each format function takes named arguments for the digits: Float.format(rating, locale, fraction: 0..=1) writes 4.8125 as 4,8 in German. The digits after the point are one range, at least its start and at most its end, so a backwards range is a compile error. Int.format, Float.format and Decimal.format list every option and how each type rounds.

Money.format writes a price the way a reader of a locale expects: $1,299.50 in American English and 1.299,50 $ in German. Money shows it, with the ways to show the currency, and how to read a price someone typed.

An American writes October 20 as 10/20/26, and a German as 20.10.26. The types in std::calendar (Date, Time, NaiveDateTime and DateTime) each have a format that writes them for a locale. style: picks how long the text is: .Short, .Medium (the default for a date), .Long or .Full.

import
    std::calendar.{Date, DateTime}
    std::io
end

fn main()
    ships = Date"2026-10-20"
    order = DateTime"2026-10-20T17:30:00-04:00[America/New_York]"

    [Locale"en-US", Locale"de"]
    |> Iter.each(fn locale ->
        io.print(Date.format(ships, locale, style: .Full))
        io.print(Date.format(ships, locale, style: .Short))
        io.print(DateTime.format(order, locale))
        io.print(DateTime.format(order, locale, date: .Long, time: .Long))
    end)
end

A time is written with the clock the locale uses: 5:30 PM in American English and 17:30 in German. Time.format writes a time on its own. A DateTime takes a style for each half, as date: (.Medium by default) and time: (.Short). .Long and .Full times show the offset from UTC, here four hours behind.

A style decides which fields appear. To choose them yourself, say what you want with a skeleton: a few letters for each field, in any order, where the number of letters sets the width: MMMM is the month’s full name and MMM its short name, EEEE the weekday’s name, d the day of the month, and y the year. CLDR then finds the order and punctuation each locale uses for those fields.

import
    std::calendar.{Date, DateFields}
    std::io
end

fn main()
    ships = Date"2026-10-20"

    [Locale"en-US", Locale"de"]
    |> Iter.each(fn locale ->
        day = Date.format_fields(ships, locale, DateFields"MMMMEEEEd")
        month = Date.format_fields(ships, locale, DateFields"yMMM")
        io.print("${locale}: ${day} | ${month}")
    end)
end

The skeleton is a DateFields for a Date, a TimeFields for a Time, and a DateTimeFields for both. The compiler checks its letters, so a time field in a DateFields is an error.

A file name, a log line or another program’s input needs a date that is the same for every reader. A DatePattern spells out the exact layout, with yyyy for the year, MM for the month and dd for the day: Date.to_string_with(ships, DatePattern"yyyyMMdd") is 20261020, and Date.parse_with reads such text back. A fixed pattern holds numbers only. A month’s name belongs to a language, so the compiler refuses one in a pattern and points you to a skeleton:

error: typed literal DatePattern"dd MMM yyyy" is invalid: invalid format: `MMM` writes the month's name, which is a word of a language: a fixed pattern writes numbers, the same in every locale; write it for a reader with a skeleton and a locale, as Date.format_fields(date, locale, DateFields"yMMMd")

TimeUnit.format_relative writes a time relative to now: “in 3 days”, or “yesterday” when the language has a word for it. It takes the count, the locale and the unit. Duration.format writes a length of time, such as how long delivery takes.

import
    std::calendar.TimeUnit
    std::duration.Duration
    std::io
end

fn main()
    [-1, 3, -3]
    |> Iter.each(fn n ->
        en = TimeUnit.format_relative(n, Locale"en-US", .Day)
        pl = TimeUnit.format_relative(n, Locale"pl", .Day)
        io.print("${n}: ${en} | ${pl}")
    end)

    delivery = Duration.minutes(90)
    io.print(Duration.format(delivery, Locale"en-US"))
    io.print(Duration.format(delivery, Locale"pl"))
    io.print(Duration.format(delivery, Locale"en-US", width: .Narrow))
end

width: takes a DurationWidth: .Long (the default), .Short or .Narrow (1h 30m).

The page shows who else is looking at an item. String.join_list joins the names the way the reader’s language joins them:

import std::io

fn main()
    watching = ["Anna", "Ben", "Chloé"]

    [Locale"en-US", Locale"en-GB", Locale"pl"]
    |> Iter.each(fn locale ->
        io.print("${locale}: ${String.join_list(watching, locale)}")
    end)

    dbg String.join_list(["Anna", "Ben"], Locale"en-US")
    dbg String.join_list(["S", "M", "L"], Locale"en-US", style: .Or)
    dbg String.join_list(["S", "M", "L"], Locale"pl", style: .Or)
    dbg String.join_list(["2 lb", "3 oz"], Locale"en-US", style: .Unit)
end

American English puts a comma before “and”, and British English doesn’t. Polish uses “i” for “and” and “lub” for “or”.

The style argument (ListStyle) says what the list means: all of the items (And, the default), one of them (Or), or the parts of one amount (Unit). To join numbers, format each number first, then join the strings.

When a reader types a quantity, a price or a date, read it with parse_in and the same locale you used to show it to them. The locale matters: 1.200 means twelve hundred in German but one point two in English.

import std::io

fn main()
    dbg Int.parse_in("1,200", Locale"en-US")
    dbg Int.parse_in("1.200", Locale"de")
    dbg Int.parse_in("1200", Locale"de")
    dbg Int.parse_in("1.200", Locale"en-US")
    dbg Decimal.parse_in("49,90", Locale"de")
    dbg Int.parse_in(" 3 ", Locale"en-US")
    dbg Int.parse_in(" 3 ", Locale"en-US", lenient: True)

    case Int.parse_in("2.5", Locale"en-US")
        Ok(n)  -> io.print("quantity ${n}")
        Err(e) -> io.print("not a quantity: ${e}")
    end
end

By default parse_in is strict: it reads what format writes, so " 3 " with its spaces is an error, though 1200 without its separator reads. An error is a NumberParseError, which says what went wrong and where. at counts characters from the start of the text.

lenient: True accepts more, such as spaces around the number. Int.parse_in lists what each way takes. Decimal.parse_in keeps the digits the reader typed, so 49,90 becomes 49.90d.

Money.parse_in reads a price the same way, as the Money chapter shows. Date.parse_in reads a date written in a locale’s style, .Short unless you pass another:

import std::calendar.Date

fn main()
    us = Locale"en-US"

    dbg Date.parse_in("10/20/26", us)
    dbg Date.parse_in("10/20/2026", us)
    dbg Date.parse_in("10/20/2026", us, lenient: True)
    dbg Date.parse_in("2/31/26", us)
    dbg Date.parse_in("Oct 20, 2026", us, style: .Medium)
end

lenient: True also accepts a four-digit year where the locale writes two. A date that doesn’t exist, such as February 31, is an error even when it is written correctly. Date.parse_in lists the rest.

The examples so far wrote each locale in the program. A real program learns the reader’s locale while it runs.

When the locale comes from outside, such as a web address or a setting, use Locale.parse. The LANG environment variable on Linux and macOS uses a different spelling, such as pl_PL.UTF-8, which Locale.from_posix reads.

fn main()
    dbg Locale.parse("EN-us")
    dbg Locale.parse("pt_BR")
    dbg Locale.from_posix("pl_PL.UTF-8")
    dbg Locale.fallbacks(Locale"es-MX")
end

Locale.parse fixes the capital letters, so EN-us becomes en-US. pt_BR, with an underscore, is the LANG spelling, so Locale.parse turns it down and suggests pt-BR. Locale.from_posix accepts it and ignores the .UTF-8 at the end.

When Nomi has no rules for a locale, it uses the nearest one that it has. Locale.fallbacks shows the order it tries. Mexican Spanish (es-MX) falls back to Latin American Spanish (es-419), then to Spanish (es).

The compiler checks a literal without slots, as Typed Literals explains. Locale"pt_BR" gives this error:

error: typed literal Locale"pt_BR" is invalid: a locale tag separates subtags with `-`, not `_`: write `pt-BR` (Locale.from_posix reads a POSIX value)

A browser tells each website which languages its reader prefers, best first. The shop has pages in only a few languages. Locale.negotiate picks the one that suits the reader best, or a default when none comes close:

once shop = [Locale"en", Locale"de", Locale"pl", Locale"pt"]

fn page_locale(wanted: List<Locale>) -> Locale
    Locale.negotiate(wanted, shop, Locale"en")
end

fn main()
    dbg page_locale([Locale"pt-BR", Locale"en-US"])
    dbg page_locale([Locale"de-AT"])
    dbg page_locale([Locale"ja", Locale"pl"])
    dbg page_locale([Locale"ja"])
end

A reader from Brazil gets Portuguese, and a reader from Austria gets German. The third reader wants Japanese first. The shop has no Japanese, so they get their second choice, Polish. The last reader wants only Japanese and gets the default, English.

A program usually keeps the reader’s locale in an app field. You can call the field anything; locale is the usual name. boot sets a default. Code that handles one request replaces it with a with line, which lasts until the request is done. Std’s format functions don’t read the field, so pass App.locale to them, as cart_total does:

import std::io

struct App
    locale: Locale
end

struct Request
    path:   String
    accept: List<Locale>
end

once shop = [Locale"en", Locale"de", Locale"pl"]

fn boot() -> Result<App, String>
    Ok(App{locale: Locale"en"})
end

fn main()
    [
        Request{path: "/cart", accept: [Locale"de-AT", Locale"en"]},
        Request{path: "/cart", accept: [Locale"ja"]},
    ]
    |> Iter.each(handle)
end

fn handle(request: Request)
    reader = Locale.negotiate(request.accept, shop, App.locale)
    with App.locale = reader

    total = cart_total(1299.50d)
    io.print("${request.path} in ${App.locale}: ${total}")
end

fn cart_total(total: Decimal) -> String
    Decimal.format(total, App.locale)
end

accept stands in for the list of languages a browser sends. In a real program, boot would take the default from the LANG environment variable with Locale.from_posix. A library can’t see your app fields, so a library function that writes text for people should take a Locale argument.

A program carries the CLDR data of only the locales its nomi.toml lists, as Translating Text explains; each example here lists none, so it carries every locale.

The shop’s staff page lists customers by name. Iter.sort puts strings in the order of their bytes, which is no language’s order: every name that starts with an accented letter comes after Z. Each language also has its own alphabet. German puts Ä with A, Swedish puts Å, Ä and Ö after Z, and Polish puts Ś after S and Ż after Z.

A Collator compares strings the way readers of one language order them. Make one for the locale, then sort with its compare:

import
    std::collation.Collator
    std::io
end

fn main()
    customers = ["Zorn", "Żak", "Śliwa", "Sowa", "Öberg", "Abel", "Åberg", "Ärlig"]

    [Locale"de", Locale"sv", Locale"pl"]
    |> Iter.each(fn locale ->
        by_name = Collator.new(locale)
        sorted = Iter.sort_with(customers, &Collator.compare(by_name, &1, &2))
        io.print("${locale}: ${String.join(sorted, ", ")}")
    end)

    io.print("bytes: ${String.join(Iter.sort(customers), ", ")}")
end

In German, Śliwa sorts as if it were Sliwa, so it comes before Sowa. In Polish, Ś is a letter of its own after S, so Śliwa comes after Sowa. Make a collator once and use it for the whole sort.

Collator.new takes options, such as numeric: True, which puts order-9 before order-10. The Collator reference lists the rest.

Upper and lower case depend on the language too. String.uppercase and String.lowercase follow one rule for every language. Turkish has a dotted İ and a dotless ı, so String.uppercase_in and String.lowercase_in take the locale. To match text without regard to case, compare the results of String.fold_case:

fn main()
    dbg String.uppercase("istanbul")
    dbg String.uppercase_in("istanbul", Locale"tr")
    dbg String.lowercase_in("KIRMIZI", Locale"tr")
    dbg String.fold_case("Straße") == String.fold_case("STRASSE")
end

A type can describe itself in two ways. Display gives text that is the same for everyone, used by "${...}" and in logs. Localize gives text for a reader in a given locale. Its one function is localize(value, locale). Int, Float, Decimal, Money, Duration and the calendar types implement it with their format function, and a String gives itself back. Give your own type both when it is shown to programs and to people:

import
    std::io
    std::localize.Localize
end

struct Weight
    grams: Int
end

impl Display for Weight
    fn to_string(w: Weight) -> String
        "${w.grams}g"
    end
end

impl Localize for Weight
    fn localize(w: Weight, locale: Locale) -> String
        kilograms = Int.to_decimal(w.grams) / 1000d
        "${Decimal.format(kilograms, locale)} kg"
    end
end

fn main()
    parcel = Weight{grams: 1250}

    io.print("order-1042,${parcel}")
    io.print("en-US: ships at ${Localize.localize(parcel, Locale"en-US")}")
    io.print("de: ships at ${Localize.localize(parcel, Locale"de")}")
end

The first line is a CSV row for another program, so it uses Display. The other two are for people, so they use Localize with each reader’s locale. The next chapter uses Localize to put values into translated sentences.