Skip to content

Messages & plurals

Format ICU MessageFormat strings — placeholders, numbers, and especially pluralisation and gender/word selection — without hardcoding any language's grammar rules. A single pattern adapts: English needs one/other, Arabic needs six categories, and message() picks the right branch from CLDR for you.

The pattern language

A pattern is plain text with {…} placeholders. There are four placeholder shapes:

Shape Example Renders
Simple Hello, {name}! substitutes the argument as-is
Number {n, number} · {n, number, integer} · {n, number, percent} locale-formatted number
Plural {n, plural, one {# item} other {# items}} picks a branch by plural category; # is the value
Select {g, select, female {her} male {his} other {their}} picks a branch by exact string match

Inside a plural/selectordinal branch, # is replaced by the (locale-formatted) number. Two refinements:

  • Exact matches — =0 {none} one {# item} other {# items} uses the =0 branch when the value is exactly 0, before falling back to the category.
  • offset:n — {n, plural, offset:1 =0 {nobody} one {you and # other} other {you and # others}} subtracts n from # (for "you and 2 others" style phrasing).

An other branch is required in every plural/selectordinal/select — it's the fallback when no category matches. Escape a literal brace or # by wrapping it in single quotes: '{', '#', and '' for a literal apostrophe.

Messages

Cosmo c = new Cosmo("en");
c.message("{0, plural, one {# file} other {# files}}", 3); // varargs (positional)
// "3 files"
c.message("{0,number,integer} of {1,number}", 4560, 0.2);
// "4,560 of 0.2"
c.message("{0, select, female {She} male {He} other {They}} replied", "female");
// "She replied"

Named vs positional arguments

Pass positional arguments through varargs ({0}), or named arguments in a Map ({name}). ICU MessageFormat supports number, date, time, and spellout arguments, as well as plural and selection branches.

Ordinals in messages

selectordinal works like plural but uses ordinal categories — the "1st / 2nd / 3rd" wording rules:

For ordinal text such as "22nd" without writing branches, use ordinal().

Plural category

Sometimes you want the raw decision rather than a formatted message — e.g. to pick an image or a CSS class. pluralCategory() returns the LDML category a number falls into for the locale, the same choice message() makes internally.

Cosmo en = new Cosmo("en");
en.pluralCategory(1);           // "one"
en.pluralCategory(2);           // "other"
en.pluralCategory(2, true);     // "two"
new Cosmo("ar").pluralCategory(0); // "zero"

Returns one of zero, one, two, few, many, other. Pass ordinal = true for ordinal rules instead of cardinal.

Which categories does a locale use?

The set varies wildly: English has one/other (cardinal), Arabic has all six, Japanese has only other. Write every plural branch you reference, but always keep other — it covers any category you didn't spell out.