Is there an easy way in C# to create Ordinals for a number? For example:
Can this be done through String.Format()
or are there any functions available to do this?
This page gives you a complete listing of all custom numerical formatting rules:
As you can see, there is nothing in there about ordinals, so it can't be done using String.Format
. However its not really that hard to write a function to do it.
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";
}
}
Update: Technically Ordinals don't exist for <= 0, so I've updated the code above. Also removed the redundant ToString()
methods.
Also note, this is not internationalized. I've no idea what ordinals look like in other languages.