Microsoft & .NET.NET1st, 2nd, 3rd: Using Ordinal Numbers in your App

# 1st, 2nd, 3rd: Using Ordinal Numbers in your App

Developer.com content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

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 might use this GetOrdinal function in code. Enjoy:

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

Karl Moore (MCSD, MVP) is an experience author living in Yorkshire, England. He is the author of numerous technology books, including the new Ultimate VB .NET and ASP.NET Code Book (ISBN 1-59059-106-2, \$49.99), plus regularly features at industry conferences and on BBC radio. Moore also runs his own creative consultancy, White Cliff Computing Ltd. Visit his official Web site at www.karlmoore.com.

# # #

Subscribe to Developer Insider for top news, trends & analysis