Tuesday, January 30, 2007

Ordinal Numbers in C# - like 1 as 1'st 3 as 3'rd

I got the idea somewhere but when I needed to have my repeater control show traveler numbers like 1'st traveler, 2'nd traveler e.t.c., I came up with this simple logic that takes in int and returns the string as ordinal number. Here it is...

private string GetNumberAsString(int TheNumber)

{

int condition1, condition2;

condition1 = (TheNumber % 100);

condition2 = (TheNumber % 10);

if (condition1 == 11 || condition1 == 12 || condition1 == 13) return (TheNumber.ToString() + "th");

switch (condition2)

{

case 1:

return (TheNumber.ToString() + "st");

case 2:

return (TheNumber.ToString() + "nd");

case 3:

return (TheNumber.ToString() + "rd");

default:

return (TheNumber.ToString() + "th");

}

}



Love coding!

2 comments:

Anonymous said...

Very nice sample of clear, concise code.

This can easily be added to a custom CultureInfo class to allow for extending number formatting, or use .NET 3.0 extension methods to add it to the Int32 class.

burton.rodman said...

since the c# switch doesn't translate very well to vb, let me offer this vb version:

Public Function ToOrdinal(ByVal value As Integer) As String

If value Mod 100 > 10 And value Mod 100 < 20 Then
Return value.ToString & "th"
Else
Select Case value Mod 10
Case 1
Return value.ToString & "st"
Case 2
Return value.ToString & "nd"
Case 3
Return value.ToString & "rd"
Case Else
Return value.ToString & "th"
End Select
End If

End Function