19 Dec 2013

Ordinal Suffix in C# / .NET e.g. the postfix part of 1st, 2nd, 3rd, 4th

DEFINITIVE ANSWER TIME :)

Here's a natty extension method to get the Ordinal Suffix of a number.

public static string GetOrdinalSuffix(this int number, bool includeNumberInResult = false)
{
 string suffix = "th";
 if (Math.Floor(number / 10f) % 10 != 1)
 {
  switch (number % 10)
  {
   case 1:
    suffix = "st";
    break;
   case 2:
    suffix = "nd";
    break;
   case 3:
    suffix = "rd";
    break;
  }
 }
 return includeNumberInResult ? number + suffix : suffix;
}

Yes, this handles teens correctly i.e.

1: 1st
11: 11th
21: 21st
111: 111th
1011: 1011th

etc.....

No comments:

Post a Comment

Comments are very welcome but are moderated to prevent spam.

If I helped you out today, you can buy me a beer below. Cheers!