Library code snippets

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)

Comments

  1. 07 Apr 2009 at 05:31
    May I offer this much simpler version: Public Function ToOrdinal(ByVal value As Integer) As String If value Mod 100 > 10 And value Mod 100 < 20 Then Return value.ToString & "th" Else Select Case value Mod 10 Case 1 Return value.ToString & "st" Case 2 Return value.ToString & "nd" Case 3 Return value.ToString & "rd" Case Else Return value.ToString & "th" End Select End If End Function

Leave a comment

Sign in or Join us (it's free).

Karl Moore

Related podcasts

  • xpert to Expert: Inside Concurrent Basic (CB)

    "Concurrent Basic extends Visual Basic with stylish asynchronous concurrency constructs derived from the join calculus. Our design advances earlier MSRC work on Polyphonic C#, Comega and the Joins Library. Unlike its C# based predecessors, CB adopts a simple event-like syntax familiar to VB progr...

Want to stay in touch with what's going on? Follow us on twitter!