Click here to Skip to main content
Click here to Skip to main content

Tagged as

Go to top

Ordinal suffixes in English for the nth degree

, 13 Jun 2011
Rate this:
Please Sign up or sign in to vote.
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 + "<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)

Share

About the Author

GAMerritt

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... PinmvpLuc Pattyn12-Jun-11 14:59 

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

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

| Advertise | Privacy | Mobile
Web01 | 2.8.140916.1 | Last Updated 14 Jun 2011
Article Copyright 2011 by GAMerritt
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid