ExtensionMethod.NET Home of 875 C#, Visual Basic, F# and Javascript extension methods

AddOrdinal

Add an ordinal to a number,

Source

/// <summary>
/// Adds an ordinal to a number
/// </summary>
/// <param name="number">The number to add the ordinal too.</param>
/// <returns>A string with an number and ordinal</returns>
public static string AddOrdinal(this int number)
{
    if (number <= 0)
    {
        return number.ToString();
    }

    switch (number % 100)
    {
        case 11:
        case 12:
        case 13:
            return number + "th";
    }

    switch (number % 10)
    {
        case 1:
            return number + "st";

        case 2:
            return number + "nd";

        case 3:
            return number + "rd";

        default:
            return number + "th";
    }
}

Example

int number = 1;

var ordinal = number.AddOrdinal(); // 1st

Author: K M Thomas

Submitted on: 25 mrt 2016

Language: C#

Type: System.Int32

Views: 3763