Created
October 26, 2016 03:14
-
-
Save robyoder/7fc663d347127bab6cd799b78de0f539 to your computer and use it in GitHub Desktop.
Ordinal Number Strings in TypeScript
This file contains hidden or 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
| // 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"; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
nice job, thanks!