Is there an easy way in .NET to get "st", "nd", "rd" and "th" endings for numbers?
It's a function which is a lot simpler than you think. Though there might be a .NET function already in existence for this, the following function (written in PHP) does the job. It shouldn't be too hard to port it over.
function ordinal($num) {
$ones = $num % 10;
$tens = floor($num / 10) % 10;
if ($tens == 1) {
$suff = "th";
} else {
switch ($ones) {
case 1 : $suff = "st"; break;
case 2 : $suff = "nd"; break;
case 3 : $suff = "rd"; break;
default : $suff = "th";
}
}
return $num . $suff;
}
Simple, clean, quick
private static string GetOrdinalSuffix(int num)
{
string number = num.ToString();
if (number.EndsWith("11")) return "th";
if (number.EndsWith("12")) return "th";
if (number.EndsWith("13")) return "th";
if (number.EndsWith("1")) return "st";
if (number.EndsWith("2")) return "nd";
if (number.EndsWith("3")) return "rd";
return "th";
}
Or better yet, as an extension method
public static class IntegerExtensions
{
public static string DisplayWithSuffix(this int num)
{
string number = num.ToString();
if (number.EndsWith("11")) return number + "th";
if (number.EndsWith("12")) return number + "th";
if (number.EndsWith("13")) return number + "th";
if (number.EndsWith("1")) return number + "st";
if (number.EndsWith("2")) return number + "nd";
if (number.EndsWith("3")) return number + "rd";
return number + "th";
}
}
Now you can just call
int a = 1;
a.DisplayWithSuffix();
or even as direct as
1.DisplayWithSuffix();
No, there is no inbuilt capability in the .NET Base Class Library.