Click here to Skip to main content
15,884,628 members
Articles / Programming Languages / C#
Tip/Trick

Ordinal suffixes in English for the nth degree

Rate me:
Please Sign up or sign in to vote.
4.00/5 (2 votes)
13 Jun 2011CPOL 20.5K   5   1
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.


C#
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:


C#
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 + "<sup>";
  res = res+thstndrd.Substring(k << 1, 2);
  if (forHTML) res = res + "</sup>";
  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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
Writer, designer, inventor, musician, observer, and critic with many years of experience in each of these areas. I can do without the approval of "experts" because I believe candid statements and penetrating analysis bring greater rewards than a "pat on the back". And if I have something to say when you're not listening, I tell someone else about it.

Comments and Discussions

 
GeneralNice little function, a bit cryptic though, and probably not... Pin
Luc Pattyn12-Jun-11 14:59
sitebuilderLuc Pattyn12-Jun-11 14:59 
Nice little function, a bit cryptic though, and probably not quite correct. 22 gives 22th.
I guess there is a bug in k = (int)(v % 100);
BTW: you don't need the variable w at all. Start setting res to v.ToString, then reduce v to v%100, later do k = (int)(v % 10), and all is well.

Smile | :)

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.