p2p.wrox.com Forums

p2p.wrox.com Forums (http://p2p.wrox.com/index.php)
-   C# (http://p2p.wrox.com/forumdisplay.php?f=22)
-   -   Is there an easy way to create ordinals in C#? (http://p2p.wrox.com/showthread.php?t=100239)

Louis5149 June 11th, 2019 02:00 AM

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 String.Format() or are there any functions available to do this?

Henry3194 June 13th, 2019 01:46 AM

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

http://msdn.microsoft.com/en-us/library/0c899ak8.aspx

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.

Code:

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";
        default:
            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.


All times are GMT -4. The time now is 02:37 PM.

Powered by vBulletin®
Copyright ©2000 - 2020, Jelsoft Enterprises Ltd.
© 2013 John Wiley & Sons, Inc.