Question

I have an integer in an Access database, which is being displayed in ASP.NET. The integer represents the position achieved by a competitor in a sporting event (1st, 2nd, 3rd, etc.), and I'd like to display it with a standard suffix like 'st', 'nd', 'rd' as appropriate, rather than just a naked number.

An important limitation is that this is for an assignment which specifies that no VB or C# code be written (in fact it instructs code behind files to be deleted entirely). Ideally I'd like to use a standard format string if available, otherwise perhaps a custom string (I haven't worked with format strings much, and this isn't high enough priority to dedicate significant time to*, but I am very curious about whether there's a standard string for this).

(* The assignment is due tonight, and I've learned the hard way that I can't afford to spend time on things that don't get the marks, even if they irk me significantly.)

Was it helpful?

Solution

Unfortunately, there is no standard format string to do this. But it's not that hard to write:

public static string ToOrdinal(this int i, string format)
{
   string suffix = "th";
   switch (i%100)
   {
       case 11:
       case 12:
       case 13:
          //deliberately empty
          break;
       default:
          switch (i%10)
          {
              case 1:
                  suffix = "st";
                  break;
              case 2:
                  suffix = "nd";
                  break;
              case 3:
                  suffix = "rd";
                  break;
           }
           break;
   }
   return i.ToString(format) + suffix;
}

OTHER TIPS

You could try this

public static string FormatOrdinalNumber(int number)
{
    if (number == 0) return "0";
    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";
    }
    return number + "th";
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top