C# Ordinal String Extension

C

Let’s explore creating an extension method to convert a number to an ordinal value, e.g. 1st, 2nd, 3rd, etc.

Leveraging modulus

Using the modulus function, you can check the results using a case statement to determine if you append st, nd, rd, or th. If you’re looking for more practical examples I recommend exploring more about the CASE Statement in SQL.

To start we need to create a static class for our integer extension function. Here is a basic template of the extension class that contains a single function called: Ordinal

[code]
namespace Common.Extensions
{
public static class IntegerExtensions
{
///

/// Get the ordinal value of positive integers.
///

/// The number.
/// Ordinal value of positive integers, or if less than 1.
public static string Ordinal(this int number)
{
return string.Empty;
}
}
}
[/code]

Currently the Ordinal function just returns an empty string so the code will compile. Let’s now look at the guts of the function:

[code]
var numberAsString = number.ToString();

// Negative and zero have no ordinal representation
if (number < 1)
{
return numberAsString;
}

number %= 100;
if ((number >= 11) && (number <= 13))
{
return numberAsString + “th”;
}

switch (number % 10)
{
case 1: return numberAsString + “st”;
case 2: return numberAsString + “nd”;
case 3: return numberAsString + “rd”;
default: return numberAsString + “th”;
}
[/code]

The function starts by checking if the number is less than 1. When it is, it simply returns the number as a string. The number is then modulated by 100. If the result is between 11 and 13 it will end in th.

Then the number is modulated again by 10. When 1, it returns st, 2 returns nd, 3 returns rd, and all others return th.

Here is a sample of how to use this function:

[code]
int number = 5;
Console.WriteLine(number.Ordinal());
[/code]

The above code would output 5th.

About the author

By Jamie

My Books