Skip to content

Instantly share code, notes, and snippets.

@MarketingPip
Created August 3, 2023 07:41
Show Gist options
  • Save MarketingPip/8c6c6b4447c7755085a9cac06368a9d9 to your computer and use it in GitHub Desktop.
Save MarketingPip/8c6c6b4447c7755085a9cac06368a9d9 to your computer and use it in GitHub Desktop.
A JavaScript function for converting number to ordinal.
function getOrdinal(number) {
if (typeof number !== 'number' || isNaN(number)) {
throw new Error('Input must be a valid number');
}
const suffixes = ['th', 'st', 'nd', 'rd'];
const remainder = number % 100;
const suffix = suffixes[(remainder - 20) % 10] || suffixes[remainder] || suffixes[0];
return number + suffix;
}
// Examples:
console.log(getOrdinal(1)); // Output: 1st
console.log(getOrdinal(22)); // Output: 22nd
console.log(getOrdinal(123)); // Output: 123rd
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment