- Back to Home »
- ASP.Net , C# »
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.
- public static string AddOrdinal(int num)
- {
- if (num <= 0) return num.ToString();
- switch (num % 100)
- {
- case 11:
- case 12:
- case 13:
- return num + "th";
- }
- switch (num % 10)
- {
- case 1:
- return num + "st";
- case 2:
- return num + "nd";
- case 3:
- return num + "rd";
- default:
- return num + "th";
- }
- }
Another way:
- public static string[] SuffixLookup = { "th","st","nd","rd","th","th","th","th","th","th" };
- public static string AppendOrdinalSuffix(int number)
- {
- if (number % 100 >= 11 && number % 100 <= 13)
- {
- return number + "th";
- }
- return number + SuffixLookup[number% 10];
- }
And the more simplest way:
- private static string GetOrdinalSuffix(int num)
- {
- if (num.ToString().EndsWith("11")) return "th";
- if (num.ToString().EndsWith("12")) return "th";
- if (num.ToString().EndsWith("13")) return "th";
- if (num.ToString().EndsWith("1")) return "st";
- if (num.ToString().EndsWith("2")) return "nd";
- if (num.ToString().EndsWith("3")) return "rd";
- return "th";
- }