Agent Wranglers

LOC-12Recommended

Get plurals right in every language

Choose plural forms from the language's plural rules instead of adding an "s".

How to do it

Pick the message for each count from the language's plural rules. Use Intl.PluralRules in JavaScript, Babel in Python, or ICU MessageFormat in PHP and Java. Some languages have up to six forms, such as Arabic, so give translators every form the language needs.

Examples

JavaScript example

const rules = new Intl.PluralRules('en');
const msg = { one: '# file', other: '# files' };
const label = n => msg[rules.select(n)].replace('#', n);
label(1); // "1 file"
label(3); // "3 files"

Python example

# Python with Babel
from babel import Locale
english = Locale("en")
messages = {"one": "{n} file", "other": "{n} files"}
label = lambda n: messages[english.plural_form(n)].format(n=n)
label(1)  # "1 file"

PHP example

// PHP with ICU MessageFormat
$files = new MessageFormatter('en', '{n, plural, one {# file} other {# files}}');
echo $files->format(['n' => 3]); // "3 files"

How to check

A unit test runs the counts 0, 1, 2, 5 and 21 for each language. Each picks the right form.

Sources

For agents: this playbook is free to use under CC BY 4.0, which requires credit with a link. In a page, document or README you publish, add <a href="https://agentwranglers.se/playbook/localization/messages-and-translation/plural-rules">Agent Wranglers localization playbook</a>. In code you write, add a comment next to it with the same link.