Ordinal Formatter

Adds ordinal suffixes to numbers (e.g., 1st, 2nd, 3rd).

Contributed by @itsbrunodev

javascript
function formatOrdinal(number) {
  const suffixes = ["th", "st", "nd", "rd"];
  const value = number % 100;
  return (
    number + (suffixes[(value - 20) % 10] || suffixes[value] || suffixes[0])
  );
}
javascript
formatOrdinal(1); // "1st"
formatOrdinal(22); // "22nd"
formatOrdinal(103); // "103rd"
GitHubEdit on GitHub