Mohanapriya R Mohanapriya R
Updated date Mar 15, 2024
In this article, we will learn how to convert regular numbers into their ordinal forms in C#.

Convert Number to Ordinal in C#

Ordinal numbers indicate a position or order in a series, such as first, second, third, and so on. They are different from cardinal numbers, which represent quantity. Ordinal numbers typically end in "st", "nd", "rd", or "th" depending on the last digit of the number.

Implementing the Conversion Function:

To convert a number to its ordinal form in C#, we can create a simple function that takes an integer as input and returns the corresponding ordinal string. Here's a sample implementation of such a function:

using System;

class Program
{
    static string ConvertToOrdinal(int number)
    {
        if (number <= 0)
            return number.ToString();

        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";
            default:
                return number + "th";
        }
    }

    static void Main(string[] args)
    {
        // Example usage
        for (int i = 1; i <= 10; i++)
        {
            Console.WriteLine($"{i} -> {ConvertToOrdinal(i)}");
        }
    }
}

Output:

1 -> 1st

2 -> 2nd

3 -> 3rd

4 -> 4th

5 -> 5th

6 -> 6th

7 -> 7th

8 -> 8th

9 -> 9th

10 -> 10th

Comments (0)

There are no comments. Be the first to comment!!!