Plural Localization Formatter
Languages vary in how they handle plurals of nouns or unit expressions, for example, "hour" vs "hours". Some languages have two forms, like English; some languages have only a single form; and some languages have multiple forms. The Plural Localization Formatter follows the Unicode Common Locale Data Repository (CLDR) approach to handle plurals.
CLDR uses short, mnemonic tags for these plural categories:
- zero
- one (singular)
- two (dual)
- few (paucal)
- many (also used for fractions if they have a separate class)
- other (required—general plural form—also used if the language only has a single form)
The Plural Localization Formatter supports cardinal pluralization rules to choose different text. A full list of the plural rules per locale can be found here.
To determine which plural rules to apply, the Plural Localization Formatter uses the locale of the String Table that the smart string is part of. You can override the locale with the Format Option, for example to force English, set (en) as the Format Option: {0:plural(en):is 1 item|are items}
Note: The placeholder can be used as a shorthand to use the current value.
Note: You can use a plural formatter against an IEnumerable value. In this case, the Count of the IEnumerable count is used as the plural value.
Example Smart String | Arguments | Result |
---|---|---|
I have {0:plural:an apple\|{} apples} | English Locale: 10 |
I have 10 apples |
{0} {0:банан\|{} банана\|{} бананов} | Russian Locale: 1 |
1 банана |
{0:p:{} manzana\|{} manzanas} | Spanish Locale: 2 |
2 Manzanas |
The following {0:plural:person is\|people are} impressed: {0:list:{}\|, \|, and}. |
|
The following people are impressed: bob, and alice. |
|
The following person is impressed: Mohamed. |
Custom plural rules
You can add custom plural rules to replace existing ones or create new rules. Sometimes, you might want to use a custom ruleset for particular situations without changing the default rules everywhere. To do this, define a new plural rule and reference it directly in your smart string with brackets.
The following example defines a custom plural rule for Russian that uses two plural forms instead of the standard three. When the pluralization logic requires the third form, this rule redirects it to the second form. This provides more precise control in scenarios where only two plural variations are needed.
UnityEngine.Localization.SmartFormat.Utilities.PluralRules.IsoLangToDelegate.Add("ru-custom", (val, count) =>
{
// evaluate normal Russian rules
var rule = UnityEngine.Localization.SmartFormat.Utilities.PluralRules.IsoLangToDelegate["ru"];
var index = rule(val, count);
// Add your fallback here.
// Clamp it to our expected index to prevent the exception.
return Mathf.Clamp(index, 0, 1);
});
Example: Жемчужин{count:p(ru-custom):а|ы|}
Note that the custom plural rule is invoked by placing ru-custom
inside the brackets.