
Intl.PluralRules
The Intl.PluralRules
object enables plural-sensitive formatting and plural-related language rules.
Syntax
new Intl.PluralRules([locales[, options]])
locales [Optional]
A string with a BCP 47 language tag (or array of strings).
options [Optional]
localeMatcher
type
minimumIntegerDigits
minimumFractionDigits
minimumSignificantDigits
maximumSignificantDigits
Today, we are going to explain examples using locales
and type
parameter.
type
It is the type to use. It can have two values
"cardinal" - a number that represents amount, such as 1,2,3 rather than order, such as 1st, 2nd, 3rd etc.
"ordinal" - a number such as 1st, 2nd, 3rd, 4th, that shows the position of something in a list of things.
Using Locales:-
The below example shows few variations in localized plural rules. In order to get the format of the language used in the user interface of your application, make sure to specify that language (and some auxiliary languages) using the locales argument:
Example 1:-
const pr = new Intl.PluralRules('en-US', { type:'ordinal'});
console.log(pr.select(1)); // "one"
console.log(pr.select(2)); // "two"
console.log(pr.select(3)); // "few"
console.log(pr.select(4)); // "other"
Possible Return Values
//The other possible return values are:
zero
one
two
few
many
other
Adding suffixes to ordinal numbers ("1st,'2nd' "3rd" 14th, …") requires custom logic which is often error-prone (specific to each locale!).
Intl.PluralRules
now makes our task easier. How? Let us look at another example.
Example 2:-
My requirement is that if input contains number such as 1,2,3…, output should display as 1st,2nd,3rd….
Here is the logic for the same.
const pr = new Intl.PluralRules('en', { type:'ordinal'});
const suffix = { one: 'st', two: 'nd', few:'rd', other:'th' }
const numberArray = [0, 1, 2, 3, 4, 56, 42, 32, 33, 560];
numberArray.map((x) => console.log(`${x}${suffix[pr.select(x)]}`) );
Output
//Output
"0th"
"1st"
"2nd"
"3rd"
"4th"
"56th"
"42nd"
"32nd"
"33rd"
"560th"
Hope you enjoyed and learned something new today!
![]() | ![]() | ![]() | ![]() |
Like | Comment | Save | Share |