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
Avoid hardcoded wait times  26 May 2018
Guaranteed Progression  19 May 2018
Prefer declarative method names  03 Feb 2018
Using Premeditation  27 Jan 2018
With Relocation  20 Jan 2018
Using Consolidation  13 Jan 2018
Using Semantic Types  06 Jan 2018
Using Extension Methods  30 Dec 2017
Error Methods  25 Nov 2017
Pass implementations, not representations  14 Oct 2017
More smart-code posts »
Archives
April 2010
2010