Add an ordinal suffix (1st, 2nd, 3rd, ...) to a number in Javascript

Sohail · · 3661 Views

Ordinal numbers convey information about the order of elements in a set. They show rank or position. For example: 1st, 2nd, 3rd, ...

1

Please login or create new account to add your comment.

1 comment
Iqbal
Iqbal ·

I'd personally go with something simpler like:

function ordinal(num) {
  const lastDigit = num % 10;
  const lastTwoDigits = num % 100;

  return num + (
    // 11-13 take 'th'
    (lastTwoDigits > 9 && lastTwoDigits < 14) ? 'th' :
    lastDigit === 1 ? 'st' :
    lastDigit === 2 ? 'nd' :
    lastDigit === 3 ? 'rd' : 'th'
  )
}
You may also like: