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
Related rules
- APP-14 Show relative times with the exact time beside them in Web app interface
- NTF-38 Write each notification in the recipient's language in Notifications
- LOC-13 Translate whole sentences in Localization
- LOC-24 Choose gender and other variants inside the message in Localization
- LOC-19 Fail the build on missing or broken translations in Localization
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.