Follow @endyourif rss Facebook LinkedIn

C# Ordinal String Extension C# Ordinal String Extension

Published on Mar 29, 2019

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.

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

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;

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

            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";

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:

int number = 5;

The above code would output 5th.

Tags: ASP.NET MVC and Web API Tutorial | c# | ordinal | modulus

My Books
ASP.NET MVC 5 With Bootstrap and Knockout.js
Knockout.js Building Dynamic Client-Side Applications
20 Recipes for Programming MVC 3
20 Recipes for Programming PhoneGap
Rapid Application Development with CakePHP