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)
Related articles
Related discussion
-
It's Urgent! How to hide applications on my vb.net application run
by diana_ser (2 replies)
-
RowHeader column with 2 columns in Winform DatagridView
by santosh_kumar (3 replies)
-
VB.NET Restoring a minimized form which has not got focus
by legolas123 (1 replies)
-
Why choose c# when there is Java
by Thaj06 (0 replies)
-
Change color while typing in rich text box
by Akhtar Hussain (0 replies)
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...
Comments
Leave a comment
Sign in or Join us (it's free).