Wrox Programmer Forums
Go Back   Wrox Programmer Forums > C# and C > C# 1.0 > C#
| Search | Today's Posts | Mark Forums Read
C# Programming questions specific to the Microsoft C# language. See also the forum Beginning Visual C# to discuss that specific Wrox book and code.
Welcome to the p2p.wrox.com Forums.

You are currently viewing the C# section of the Wrox Programmer to Programmer discussions. This is a community of software programmers and website developers including Wrox book authors and readers. New member registration was closed in 2019. New posts were shut off and the site was archived into this static format as of October 1, 2020. If you require technical support for a Wrox book please contact http://hub.wiley.com
  #1 (permalink)  
Old June 11th, 2019, 02:00 AM
Louis5149
Guest
 
Posts: n/a
Default 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?
  #2 (permalink)  
Old June 13th, 2019, 01:46 AM
Henry3194
Guest
 
Posts: n/a
Default

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.


Similar Threads
Thread Thread Starter Forum Replies Last Post
Chapter 4: Using the Wizard to Create Easy-to-Use Forms jsong005 BOOK: Beginning ASP.NET 4 : in C# and VB 1 August 9th, 2016 11:12 AM
Help with the CH 4 Using the Wizard to Create Easy-to-Use-Forms RogueAkula BOOK: Professional ASP.NET 4 : in C# and VB 1 December 15th, 2013 09:42 PM
Easy One ru1 Access 2 September 15th, 2006 10:36 PM
Probably easy but... AMP - Max Current BOOK: Beginning PHP, Apache, MySQL Web Development ISBN: 978-0-7645-5744-6 2 December 20th, 2004 02:55 PM
NOT Easy Enough!!! wilson Forum and Wrox.com Feedback 3 July 16th, 2004 07:14 PM





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