Last active
September 30, 2021 21:26
-
-
Save joeyred/28b21c3535c1e44dd842a4c56c7dcc44 to your computer and use it in GitHub Desktop.
Add a suffix to a number. "st", "nd", "rd", and "th".
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
/** | |
* Adds suffix to number passed. | |
* | |
* @method _addSuffixToNumber | |
* | |
* @param {number} number - The number to have a suffix added to. | |
* | |
* @return {string} - Number with suffix added. | |
*/ | |
function addSuffixToNumber(number) { | |
// Get remainder of `number` divided by 10. | |
var lastDigit = number % 10; | |
// Get remainder of `number` divided by 100. | |
var lastTwoDigits = number % 100; | |
// If lastDigit is 1 but last two digits not 1, return with added "st". | |
if (lastDigit === 1 && lastTwoDigits !== 11) { | |
return number + 'st'; | |
} | |
// If lastDigit is 2 but second to last digit is not 1, return with added "nd". | |
if (lastDigit === 2 && lastTwoDigits !== 12) { | |
return number + 'nd'; | |
} | |
// If lastDigit is 2 but second to last digit is not 1, return with added "rd". | |
if (lastDigit === 3 && lastTwoDigits !== 13) { | |
return number + 'rd'; | |
} | |
// For all other numbers, return with added "th". | |
return number + 'th'; | |
} |
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
/** | |
* Adds suffix to number passed. | |
* | |
* @method _addSuffixToNumber | |
* | |
* @param {number} number - The number to have a suffix added to. | |
* | |
* @return {string} - Number with suffix added. | |
*/ | |
function addSuffixToNumber(number: number): string { | |
// Get remainder of `number` divided by 10. | |
const lastDigit = number % 10; | |
// Get remainder of `number` divided by 100. | |
const lastTwoDigits = number % 100; | |
// If lastDigit is 1 but last two digits not 1, return with added "st". | |
if (lastDigit === 1 && lastTwoDigits !== 11) return number + 'st' | |
// If lastDigit is 2 but second to last digit is not 1, return with added "nd". | |
if (lastDigit === 2 && lastTwoDigits !== 12) return number + 'nd' | |
// If lastDigit is 2 but second to last digit is not 1, return with added "rd". | |
if (lastDigit === 3 && lastTwoDigits !== 13) return number + 'rd' | |
// For all other numbers, return with added "th". | |
return number + 'th'; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment