Improved Ordinal Numbers

ASP Best Practices

The following code is an improvement on the original function written by Travis Hawkins and handles numbers above 100 better


Date : 2007-09-11
The following code is an improvement on the original function written by Travis Hawkins.
The main flawed areas were between 10 and 20 on numbers above 100. E.g. the number 111 would return as 111st instead of 111th.

So I improved the code slightly 2 count the last 2 numbers if the number is above 100 but if the last 2 numbers are below 20 that it takes the last number into account.

Here is the code, which is commented to show what gets done where, but if you need any explanations don't hesitate to ask.








Code:
Function CreateOrdinal(i)
  Dim num, sNum, sExt
  ' checks numbers over 100
  if i > 100 then
    ' breaks numbers down to 2 last numbers
    num = right(cStr(i), 2)
    ' checks from 1 to 20 to get correct ordinal suffix for numbers like 101, 102 etc
    if num > 20 and num < 99 then
      ' breaks numbers down to last number
      num = right(cStr(i), 1)
    end if
    ' continue numbers below 100
  else
    ' breaks numbers down to 2 last numbers
    num = right(cStr(i), 1)
  end If
  select case num
    case 1
      sExt = "st"
    case 2
      sExt = "nd"
    case 3
      sExt = "rd"
    case else '4,5,6,7,8,9,0
      sExt = "th"
  end select
  ' Adds the correct ordinal suffix for numbers between 10 and 20 ('teens)
  if num > 10 and num < 20 then sExt = "th"
  sNum = i & sExt
  CreateOrdinal = sNum
End Function

Comments :

BeachBum 2007-09-13 #62

Thanks Byron,

I've used the previous Ordinal Number function for a long time without realizing it didn't handle numbers over 100 correctly. I appreciate you writing up this code.

I edited the code for format and added the Dim line but other than that it's untouched.

byronrode 2007-09-13 #63

Hi Beach Bum,

Its a pleasure. Thanks for adding the Dim, when I wrote it, I had placed the Dim in a separate file (dynamic includes were giving hassles with it being inline with the function) and forgot to replace it.

  • Search For Articles