How to Convert Number to Ordinal in C#?
Ordinal numbers typically end in "st", "nd", "rd", or "th" depending on the last digit of the number.
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.
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)