Skip to content

Instantly share code, notes, and snippets.

@robyoder
Created October 26, 2016 03:14
Show Gist options
  • Select an option

  • Save robyoder/7fc663d347127bab6cd799b78de0f539 to your computer and use it in GitHub Desktop.

Select an option

Save robyoder/7fc663d347127bab6cd799b78de0f539 to your computer and use it in GitHub Desktop.
Ordinal Number Strings in TypeScript
// I made this for something and ended up not needing it.
// It was too much fun to throw away though.
/**
* intToOrdinalNumberString converts an integer to an ordinal
* number string. For example: 1 => "1st", 12 => "12th", 23 => "23rd"
*/
export const intToOrdinalNumberString = (num: number): string => {
num = Math.round(num);
let numString = num.toString();
// If the ten's place is 1, the suffix is always "th"
// (10th, 11th, 12th, 13th, 14th, 111th, 112th, etc.)
if (Math.floor(num / 10) % 10 === 1) {
return numString + "th";
}
// Otherwise, the suffix depends on the one's place as follows
// (1st, 2nd, 3rd, 4th, 21st, 22nd, etc.)
switch (num % 10) {
case 1: return numString + "st";
case 2: return numString + "nd";
case 3: return numString + "rd";
default: return numString + "th";
}
}
@kloarubeek

Copy link
Copy Markdown

nice job, thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment