Posted by : Jebastin Thursday 19 December 2013

There is no inbuilt capability in the .NET Base Class Library to get the Ordinals. This AddOrdinal function will be useful when we needed to display the date format as 1st July -3rd October. There is nothing in there about ordinals, but it can't be done using String.Format. However it's not really that hard to write a function to do it. The following C# code is used to get the Ordinal Suffix of any number.
  1. public static string AddOrdinal(int num)
  2. {
  3.     if (num <= 0) return num.ToString();
  4.     switch (num % 100)
  5.     {
  6.         case 11:
  7.         case 12:
  8.         case 13:
  9.             return num + "th";
  10.     }
  11.     switch (num % 10)
  12.     {
  13.         case 1:
  14.             return num + "st";
  15.         case 2:
  16.             return num + "nd";
  17.         case 3:
  18.             return num + "rd";
  19.         default:
  20.             return num + "th";
  21.     }
  22. }

Another way:

  1. public static string[] SuffixLookup = { "th","st","nd","rd","th","th","th","th","th","th" };
  2.  
  3. public static string AppendOrdinalSuffix(int number)
  4. {
  5. if (number % 100 >= 11 && number % 100 <= 13)
  6. {
  7. return number + "th";
  8. }
  9. return number + SuffixLookup[number% 10];

And the more simplest way:

  1. private static string GetOrdinalSuffix(int num)
  2. {
  3.     if (num.ToString().EndsWith("11")) return "th";
  4.     if (num.ToString().EndsWith("12")) return "th";
  5.     if (num.ToString().EndsWith("13")) return "th";
  6.     if (num.ToString().EndsWith("1")) return "st";
  7.     if (num.ToString().EndsWith("2")) return "nd";
  8.     if (num.ToString().EndsWith("3")) return "rd";
  9.     return "th";

 Related Function in other languages:

PHP Code to Get Ordinal Suffix of a Number

Microsoft SQL Server Function to Get Ordinal Suffix of a Number

Leave a Reply

Subscribe to Posts | Subscribe to Comments

Link To This Post/Page

Spread The Word

Add this button to your blog:
JJ Technology Solutions

Blog Archive

Trackers

eXTReMe Tracker
facebook

- Copyright © JJ Technology Solutions - Powered by Source Code Solutions -