Created
August 3, 2023 07:41
-
-
Save MarketingPip/8c6c6b4447c7755085a9cac06368a9d9 to your computer and use it in GitHub Desktop.
A JavaScript function for converting number to ordinal.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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