Let's explore creating an extension method to convert a number to an ordinal value, e.g. 1st, 2nd, 3rd, etc.
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 Currently the Ordinal function just returns an empty string so the code will compile. Let's now look at the guts of the function: 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: The above code would output 5th. Published on Mar 29, 2019 Tags: ASP.NET MVC and Web API Tutorial
| c#
| ordinal
| modulus
Did you enjoy this article? If you did here are some more articles that I thought you will enjoy as they are very similar to the article
that you just finished reading.
No matter the programming language you're looking to learn, I've hopefully compiled an incredible set of tutorials for you to learn; whether you are beginner
or an expert, there is something for everyone to learn. Each topic I go in-depth and provide many examples throughout. I can't wait for you to dig in
and improve your skillset with any of the tutorials below.
Leveraging modulus
namespace Common.Extensions
{
public static class IntegerExtensions
{
///
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";
}
int number = 5;
Console.WriteLine(number.Ordinal());
Related Posts
Tutorials
Learn how to code in HTML, CSS, JavaScript, Python, Ruby, PHP, Java, C#, SQL, and more.