Ordinal suffixes in English for the nth degree
A short C# method to put the Grammarians in a Good Humor
Whether your ToString()
method for a numeric type returns a suffix, as in the French 'ieme', or not, you still might be able to use this one for English, which returns suffixes for 1031st, 23,589th, 403rd, and 352nd correctly; and might well do so for any other numbers you can think of within the range of the UInt32
.
public static string NUMthOF(UInt32 v)
{
string thstndrd = "thstndrd", res=""; int k; UInt32 w;
w = v; v = w % 100; res = w.ToString();
if ((v < 21) & (v > 3)) k = 0;
else k = (int)(v % 10); // Error was here, i.e., "% 100"
if (k > 3) k = 0;
res = res+thstndrd.Substring(k << 1, 2);
return res;
}
If you're a web developer, you might prefer this one instead:
public static string NUMthOF(UInt32 v, bool forHTML)
{
string thstndrd = "thstndrd", res=""; int k; UInt32 w;
w = v; v = w % 100; res = w.ToString();
if ((v < 21) & (v > 3)) k = 0;
else k = (int)(v % 10); // Error was here, too.
if (k > 3) k = 0;
if (forHTML) res = res + "";
res = res+thstndrd.Substring(k << 1, 2);
if (forHTML) res = res + "";
return res;
}
On a re-edit:
Thanks to Luc Pattyn for pointing out the fact that 22 was returning "th" for a suffix. The modulus needs to be ten in the statements above where I'd inserted one hundred.