Here’s a little utility function that adds an appropriate suffix after numbers to show them as they might be said:

/// <summary>
/// Format a number as it would be said.
/// </summary>
/// <param name="aValue">Number to format.</param>
/// <returns>Formatted number with suffix.</returns>
public static string AsSaid(this int aValue)
{
    string suffix = "th";
    if (aValue % 10 == 1 && aValue != 11)
    {
        suffix = "st";
    }
    else if (aValue % 10 == 2 && aValue != 12)
    {
        suffix = "nd";
    }
    else if (aValue % 10 == 3 && aValue != 13)
    {
        suffix = "rd";
    }
    return string.Format("{0}{1}", aValue, suffix);
}

Best used for smallish positive numbers. Original use was to generate phrases like this:

  • Twice a year on June 30th and December 31st.
  • Yearly on February 28th.

Limitations

  • Doesn’t quite give what you’d expect for negative numbers
  • Not intended to convert the whole number into words

Comments

blog comments powered by Disqus
Next Post
On Naming and Convention ...  18 Apr 2010
Prior Post
Using TypeConverters with WPF  12 Apr 2010
Related Posts
Using Constructors  27 Feb 2023
An Inconvenient API  18 Feb 2023
Method Archetypes  11 Sep 2022
A bash puzzle, solved  02 Jul 2022
A bash puzzle  25 Jun 2022
Improve your troubleshooting by aggregating errors  11 Jun 2022
Improve your troubleshooting by wrapping errors  28 May 2022
Keep your promises  14 May 2022
When are you done?  18 Apr 2022
Fixing GitHub Authentication  28 Nov 2021
Archives
April 2010
2010