Find the ordinal representation of an integer (1st, 2nd, 3rd) in C#

The following extension method returns an int's ordinal extension. For example, for the number 1103 it returns "rd" so you can make 1103rd or 1,103rd.

// Return the int's ordinal extension.
public static string OrdinalExtension(this int value)
{
// Start with the most common extension.
string extension = "th";

// Examine the last 2 digits.
int last_digits = value % 100;

// If the last digits are 11, 12, or 13, use th. Otherwise:
if (last_digits < 11 || last_digits > 13)
{
// Check the last digit.
switch (last_digits % 10)
{
case 1:
extension = "st";
break;
case 2:
extension = "nd";
break;
case 3:
extension = "rd";
break;
}
}

return extension;
}

The code is fairly simple. The only trick is to note that the extension is "th" for all numbers unless the last two digits are:

Last Two Digits Extension
1, 21, 31, etc. st
2, 22, 32, etc. nd
3, 23, 33, etc. rd

The oddballs are 11, 12, and 13, which have the "th" extension.

   

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.