The Ordinal Number Function

As a human being, I like to read my dates properly. That means “December 1st 2002”, rather than “December 1 2002”. But computers don’t have much of a clue when it comes to such quirks of the English language. They simply care for numbers—not ordinals, like “2nd” or “43rd”.

Something like that requires intelligence. And that’s exactly what the following neat function builds into your application. Pass it a number and it’ll look up the appropriate suffix through a series of Select routines, and then return the ordinal value.

Here’s the code:

Public Function GetOrdinal(ByVal Number As Integer) As String
    ' Accepts an integer, returns the ordinal suffix
   
    ' Handles special case three digit numbers ending
    ' with 11, 12 or 13 - ie, 111th, 112th, 113th, 211th, et al
    If CType(Number, String).Length > 2 Then
        Dim intEndNum As Integer = CType(CType(Number, String). _
            Substring(CType(Number, String).Length - 2, 2), Integer)
        If intEndNum >= 11 And intEndNum <= 13 Then
            Select Case intEndNum
                Case 11, 12, 13
                    Return "th"
            End Select
        End If
    End If
    If Number >= 21 Then
        ' Handles 21st, 22nd, 23rd, et al
        Select Case CType(Number.ToString.Substring( _
            Number.ToString.Length - 1, 1), Integer)
            Case 1
                Return "st"
            Case 2
                Return "nd"
            Case 3
                Return "rd"
            Case 0, 4 To 9
                Return "th"
        End Select
    Else
        ' Handles 1st to 20th
        Select Case Number
            Case 1
                Return "st"
            Case 2
                Return "nd"
            Case 3
                Return "rd"
            Case 4 To 20
                Return "th"
        End Select
    End If
End Function

Here’s how you may use this GetOrdinal function in code. Enjoy:

Dim strNumber As String
strNumber = "38" & GetOrdinal(38)
MessageBox.Show(strNumber)

You might also like...

Comments

Karl Moore

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“The question of whether computers can think is just like the question of whether submarines can swim.” - Edsger W. Dijkstra