SUN SUN - 1 year ago 42 Question

Setting Suffix after numbers in

I have a web application in VB.Net where I need to give ranks to places. After the ranks are calculated I want to put a suffix like this: 1st, 2nd, 3rd, 4th etc. Please give me idea how to put a suitable suffix on each number?

Answer Source

You can write a simple function that takes an Integer (or a Long) as an argument and returns an ordinal string like this.

Private Function Ordinal(num As Long) As String
    Dim suff As String = "th"
    If num < 4 Or num > 20 Then
        Select Case num Mod 10
            Case 1
                suff = "st"
            Case 2
                suff = "nd"
            Case 3
                suff = "rd"
        End Select
    End If
    Return num.ToString & suff
End Function

If you prefer the number to be formatted with the thousand separator, change the Return statement to

Return num.ToString("N0") & suff 'e.g. 1,234th

Call the function like this

Dim myNum as Integer = 123
Dim myOrd as String = Ordinal(myNum) 'will be 123rd