Skip to content

Instantly share code, notes, and snippets.

@joeyred
Last active September 30, 2021 21:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joeyred/28b21c3535c1e44dd842a4c56c7dcc44 to your computer and use it in GitHub Desktop.
Save joeyred/28b21c3535c1e44dd842a4c56c7dcc44 to your computer and use it in GitHub Desktop.
Add a suffix to a number. "st", "nd", "rd", and "th".
/**
* 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';
}
/**
* 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