Home > Backend Development > C++ > How Can I Easily Generate Ordinal Numbers (1st, 2nd, 3rd, etc.) in C#?

How Can I Easily Generate Ordinal Numbers (1st, 2nd, 3rd, etc.) in C#?

Mary-Kate Olsen
Release: 2025-01-14 16:16:47
Original
730 people have browsed it

How Can I Easily Generate Ordinal Numbers (1st, 2nd, 3rd, etc.) in C#?

Easily create ordinal numbers in C#

Creating ordinal numbers directly in C# (e.g., 1st, 2nd, 3rd) may not be directly supported by String.Format() or existing functions. However, there are some simple ways to achieve this.

One way is to use a custom function like this:

<code class="language-csharp">public static string AddOrdinal(int num)
{
    if (num <= 0) return num.ToString(); // 处理0和负数

    string number = num.ToString();
    if (num % 100 == 11 || num % 100 == 12 || num % 100 == 13)
    {
        return number + "th";
    }
    else
    {
        switch (num % 10)
        {
            case 1:
                return number + "st";
            case 2:
                return number + "nd";
            case 3:
                return number + "rd";
            default:
                return number + "th";
        }
    }
}</code>
Copy after login

This function receives an integer and checks its modulus to determine the appropriate ordinal suffix ("st", "nd", "rd", or "th"). For example:

<code class="language-csharp">Console.WriteLine(AddOrdinal(1));  // 输出:1st
Console.WriteLine(AddOrdinal(2));  // 输出:2nd
Console.WriteLine(AddOrdinal(3));  // 输出:3rd
Console.WriteLine(AddOrdinal(11)); // 输出:11th
Console.WriteLine(AddOrdinal(12)); // 输出:12th
Console.WriteLine(AddOrdinal(13)); // 输出:13th
Console.WriteLine(AddOrdinal(24)); // 输出:24th
Console.WriteLine(AddOrdinal(0));  // 输出:0
Console.WriteLine(AddOrdinal(-5)); // 输出:-5</code>
Copy after login

It should be noted that this code has not been internationalized and may need to be adjusted for other languages ​​where the ordinal format may be different. The improved code handles 0 and negative numbers, and handles numbers ending in 11, 12, 13 more accurately.

The above is the detailed content of How Can I Easily Generate Ordinal Numbers (1st, 2nd, 3rd, etc.) in C#?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template