Return to Snippet

Revision: 8275
at September 11, 2008 09:57 by DaveChild


Initial Code
Public Function ordinal(ByVal intNumber As Integer) As String
    If CType(intNumber, String).Length > 2 Then
        Dim intEndNum As Integer = CType(CType(intNumber, String).Substring(CType(intNumber, 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 intNumber >= 21 Then
        ' Handles 21st, 22nd, 23rd, et al
        Select Case CType(intNumber.ToString.Substring(intNumber.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 intNumber
            Case 1
                Return "st"
            Case 2
                Return "nd"
            Case 3
                Return "rd"
            Case 4 To 20
                Return "th"
        End Select
    End If
    ' If here, no match was found. Should be impossible. In fact, if we're here the day of the month is a non-number. Best not return an ordinal at all.
    Return ""
End Function

Initial URL


Initial Description


Initial Title
VB.NET Add Ordinal

Initial Tags


Initial Language
VB.NET