GateKiller GateKiller - 1 year ago 78
C# Question

Is there an easy way to create ordinals in C#?

Is there an easy way in C# to create Ordinals for a number? For example:

  • 1 returns 1st

  • 2 returns 2nd

  • 3 returns 3rd

  • ...etc

Can this be done through
or are there any functions available to do this?

Answer Source

This page gives you a complete listing of all custom numerical formatting rules:

As you can see, there is nothing in there about ordinals, so it can't be done using String.Format. However its not really that hard to write a function to do it.

public static string AddOrdinal(int num)
    if( num <= 0 ) return num.ToString();

    switch(num % 100)
        case 11:
        case 12:
        case 13:
            return num + "th";

    switch(num % 10)
        case 1:
            return num + "st";
        case 2:
            return num + "nd";
        case 3:
            return num + "rd";
            return num + "th";


Update: Technically Ordinals don't exist for <= 0, so I've updated the code above. Also removed the redundant ToString() methods.

Also note, this is not internationalised. I've no idea what ordinals look like in other languages.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download