Tuesday, 24 January, 2023 UTC


Let's see how we can add ordinal suffixes to number values in Javascript.
For example:
1  becomes 1st
6  becomes 6th
33 becomes 33rd
50 becomes 50th
Adding ordinal suffixes to numbers using Intl.PluralRules()
We have the Javascript Intl library that is like a swiss army knife toolbox for all kinds of string formating issues.
For our case, we want to use Intl.PluralRules().
By default Intl.PluralRules() will start with a cardinal default and returns the following:
const plurals = Intl.PluralRules();
plurals.select(0) // Returns "other" 
plurals.select(1) // Returns "one" 
plurals.select(2) // Returns "other"
But we can set it to ordinal and the out will be:
const plurals = new Intl.PluralRules('en-US', { type: 'ordinal' }); 
plurals.select(0); // Returns "other" 
plurals.select(1); // Returns "one" 
plurals.select(2); // Returns "two" 
plurals.select(3); // Returns "few"
Based on this we can make the following function to add suffixes such as "st" or "nd" to Javascript numbers:
let getNumberWithSuffix = (n) => {
    const plurals = new Intl.PluralRules('en-US', { type: 'ordinal' });  
    let suffixMap = {  
        "one" : "st",  
        "two" : "nd",  
        "few" : "rd",  
        "other" : "th" 
    return suffixMap[plurals.select(item)]

getNumberWithSuffix(13) // return 13th
getNumberWithSuffix(22) // return 22nd
getNumberWithSuffix(133) // return 133rd
The folks from egghead.io have a great article that gets into more detail about the Intl API and what we can do with it.
The Intl.PluralRules() is fully supported in all major browsers.
Adding ordinals suffixes to Javascript numbers without the Intl library
We can also write a plain old function to add the "st", "nd", "rd" or "th" suffixes to Javascript numbers":
const getNumberWithSuffix = (n)=> {
    const s = ["th", "st", "nd", "rd"];
    const v = n % 100;
    return n + (s[(v - 20) % 10] || s[v] || s[0]);
However, this approach may need to be changed for other languages.
By the way, here is the full list of rules for adding ordinal suffixes to numbers.
The post Add suffixes such as “st” or “nd” to number values in Javascript appeared first on Js Craft.