Tuesday, July 15, 2014

HowTo: Convert a given number into its ordinal value in VB.NET

Found this code from stackoverflow and made some small change to it,  this will convert any given number to its ordinal value.

Example:
Convert(1) will return 1st
Convert(11) will return 11th
Convert(12) will return 12th
Convert(23) will return 23rd

Public Function Convert(ByVal number As Integer) As String
        Dim ones As Integer = number Mod 10
        Dim tens As Integer = Math.Floor(number / 10) / 10
        If (number > 10 And number < 14) Then
            Return number.ToString() & "th"
        Else
            Select Case ones
                Case 1
                    Return number.ToString() & "st"
                Case 2
                    Return number.ToString() & "nd"
                Case 3
                    Return number.ToString() & "rd"
                Case Else
                    Return number.ToString() & "th"
            End Select
        End If
    End Function