# Thread: Easy Function to add a suffix to a number ie, 1st, 2nd, 3rd, etc..

1. ## Easy Function to add a suffix to a number ie, 1st, 2nd, 3rd, etc..

Hey, this isn't rocket science, but it took me a good twenty minutes of thought.. I think this should cover all positive integers from 0-infinity.

VB Code:
```Private Function addsuffix(ByVal num As Integer) As String
Dim suff As String
If num < 0 Then Return "Error"
If num < 20 Then
Select Case num
Case 1 : suff = "st"
Case 2 : suff = "nd"
Case 3 : suff = "rd"
Case 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 : suff = "th"
End Select
Else
Select Case Convert.ToString(num).Chars(Convert.ToString(num).Length - 1)
Case "1" : suff = "st"
Case "2" : suff = "nd"
Case "3" : suff = "rd"
Case Else : suff = "th"
End Select
End If
End Function```

Bill

2. ## Re: Easy Function to add a suffix to a number ie, 1st, 2nd, 3rd, etc..

I rewrote this for C# here...

The VB version of this rewrite is thus:

VB Code:
```Private Function AddOrdinalSuffix(ByVal num As Integer) As String
'can handle negative numbers (-1st, -12th, -21st)
Dim last2Digits As Integer = Math.Abs(num Mod 100)
Dim lastDigit As Integer = last2Digits Mod 10
'the only nonconforming set is numbers ending in <...eleventh, ...twelfth, ...thirteenth>
'all other numbers are as 1 thru 10 */
If ((last2Digits >= 11 AndAlso last2Digits <= 13) OrElse lastDigit > 3) Then lastDigit = 0
'lastdigit is now a number in range <   0,    1,    2,    3>
Return num.ToString() + New String() {"th", "st", "nd", "rd"}(lastDigit)
End Function```

Can anyone do this in less code?

3. ## Re: Easy Function to add a suffix to a number ie, 1st, 2nd, 3rd, etc..

(num mod 100) was a good idea to get the last two digits. Much cleaner code then mine. I'm still learning the power of OOP.. Great feedback for something so trivial, it helps me sharpen my grasp of good programming practices.

Bill

4. ## Re: Easy Function to add a suffix to a number ie, 1st, 2nd, 3rd, etc..

Also, I left the negatives out on purpose.. but the absolute value thing did pop into my mind.. I just couldn't say "negative 21st place" out loud without it seeming to me that I was violating Grammar.Spoken.English

Bill

5. ## Re: Easy Function to add a suffix to a number ie, 1st, 2nd, 3rd, etc..

I don't let petty trivialities like grammar get in the way of kickass code

I'm just wondering if its possible to do it in less than 4 lines. The C# version is more up to date and is slightly shorter than this one.

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•