number to ordinal list (1st, 2nd, 3rd...) (1 Viewer)

Status
Not open for further replies.

ozinm

Human Coffee Siphon
Local time
Today, 10:21
Joined
Jul 10, 2003
Messages
121
Hi All,
Here's a quick and nasty function to convert a number to it's ordinal representation.
e.g.
1 = 1st
2 = 2nd
3 = 3rd
etc.



Code:
Public  Function IntToOrdinalString(MyNumber As Integer) As String
    Dim sOutput As String
    Dim iUnit As Integer
    
    
    iUnit = MyNumber Mod 10
    sOutput = ""
    
    Select Case MyNumber
        Case Is < 0
            sOutput = ""
        Case 10 To 19
            sOutput = "th"
        Case Else
            Select Case iUnit
                Case 0 'Zeroth only has a meaning when counts start with zero, which happens in a mathematical or computer science context.
                    sOutput = "th"
                Case 1
                    sOutput = "st"
                Case 2
                    sOutput = "nd"
                Case 3
                    sOutput = "rd"
                Case 4 To 9
                    sOutput = "th"
            End Select
    End Select
    IntToOrdinalString = CStr(MyNumber) & sOutput
End Function

Hope it's useful for someone.!

All the best

Marc
 

mresann

Registered User.
Local time
Today, 02:21
Joined
Jan 11, 2005
Messages
347
Here is a much simpler one-line code (wrapped for clarity). The variable "lngNumber" is any whole number. The Switch function works somewhat like Select Case function, in which expressions are evaluated in order, the first one that produces a True statement (or non-zero result) provides for the value it is associated with. The last Switch argument, True, acts like a Case Else catchall.

Code:
         strCardinal = CStr(lngNumber) _
            & Switch( _
            lngNumber Mod 100 >= 11 And lngNumber Mod 100 <= 13, "th", _
            lngNumber Mod 10 = 1, "st", _
            lngNumber Mod 10 = 2, "nd", _
            lngNumber Mod 10 = 3, "rd", _
            True, "th")
 

isladogs

CID VIP
Local time
Today, 10:21
Joined
Jan 14, 2017
Messages
14,018
Post 2 approved. This is to trigger email notifications
 

NauticalGent

CopyPaster of the First Order
Local time
Today, 05:21
Joined
Apr 27, 2015
Messages
3,081
Although I suspect the overhead would be nominal, I wonder which solution has the biggest hit on resources.

It has always been my understanding that Case statements are more efficient than IIF/Switch statements. But, like I said, I imagine the difference in this case could be measures with a micrometer.
 
Status
Not open for further replies.

Users who are viewing this thread

Top Bottom