New Snippet New Snippet Recent Snippets Recent Snippets My Snippets My Snippets Web Code Search Snippets Search
Sign inor Register
Language: C#

C# Ordinals

104 Views
Copy Code Show/Hide Line Numbers
public static class Int32Extensions
{
    /// <summary>
    /// Appends an ordinal to the given integer value.  Reformatted from here:
    /// http://stackoverflow.com/questions/20156/is-there-an-easy-way-to-create-ordinals-in-c/20175#20175
    /// </summary>
    /// <param name="value"></param>
    /// <returns></returns>
    public static string ToStringWithOrdinal(this int value)
    {
        string suffix = null;
        int absValue = Math.Abs(value);
 
        switch (absValue % 100)
        {
            case 11:
            case 12:
            case 13:
                suffix = "th";
                break;
        }
 
        if (suffix == null)
        {
            switch (absValue % 10)
            {
                case 1:
                    suffix = "st";
                    break;
 
                case 2:
                    suffix = "nd";
                    break;
 
                case 3:
                    suffix = "rd";
                    break;
 
                default:
                    suffix = "th";
                    break;
            }
        }
 
        return value.ToString() + suffix;
    }
}
by Jon Sagara
  November 02, 2009 @ 1:20pm
Tags:
Comment:
Adds ordinal suffixes to Int32 values.

Add a comment


Report Abuse
brought to you by:
West Wind Techologies


If you find this site useful and use it frequently please consider making a donation to support this free service.
Donate