Explain Codes LogoExplain Codes Logo

Add st, nd, rd and th (ordinal) suffix to a number

javascript
functions
performance
best-practices
Alex KataevbyAlex Kataev·Dec 11, 2024
TLDR

Need a function to dynamically append the correct English ordinal suffix (st, nd, rd, or th) to a number? Below lies your treasure:

function addOrdinal(n) { // Define suffixes as an array var s = ["th", "st", "nd", "rd"], // Check the final two digits v = n % 100; // Do magic ✓ return n + (s[(v - 20) % 10] || s[v] || s[0]); } console.log(addOrdinal(1)); // 1st? No, this is Patrick! console.log(addOrdinal(2)); // And this is Patrick's 2nd friend console.log(addOrdinal(3)); // Lord of the 3rd digit console.log(addOrdinal(11)); // Combine 11 herbs and spices, get 11th chicken console.log(addOrdinal(22)); // Two little ducks went 22nd console.log(addOrdinal(123)); // 123rd day of the year, you're just getting started

My friend, this function maps last digits to the ordinal suffixes, cunningly handling exceptions. Copy and use addOrdinal and enjoy your abstract celebration of numbers.

Advanced usage and edge cases

Delve deeper into the addOrdinal function and discover more treasures hidden beneath its surface!

Considering negative numbers

Negative, or antisocial, numbers deserve their place at the ordinal party too:

function addOrdinal(n) { let absValue = Math.abs(n); // Remove any angst/negativity ... return (n < 0 ? "-" : "") + absValue + (s[(absValue - 20) % 10] || s[absValue] || s[0]); }

Modern "cool kids" syntax

const addOrdinal = n => { const s = ["th", "st", "nd", "rd"]; const v = n % 100; return `${n}${s[(v-20)%10] || s[v] || s[0]}`; // Welcome to ES6, my old friend };

Adding moment.js to the mix

moment.localeData().ordinal(n); // I can speak your language, whatever it may be!

Use moment.js if your code needs a special language touch.

Diving deeper with special cases

Special cases always suit up and shine:

Locale-specific suffixes

Extension to support multiple languages is possible, remember, coding is universal!

Prioritizing performance

Code performance remains crucial for memory usage and CPU time efficiency.

Testing large numbers

Pushing the computational limits by checking the function with large numbers can be revealing!