Home > Backend Development > C++ > How Can I Efficiently Create Ordinal Numbers (e.g., 1st, 2nd, 3rd) in C#?

How Can I Efficiently Create Ordinal Numbers (e.g., 1st, 2nd, 3rd) in C#?

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

How Can I Efficiently Create Ordinal Numbers (e.g., 1st, 2nd, 3rd) in C#?

Creating ordinal numbers in C#: a convenient way

Representing numbers as ordinal numbers (e.g., 1st, 2nd, 3rd, etc.) can be a programming challenge in C#.

String.Format() can be implemented?

Unfortunately, String.Format() does not directly support ordinal formatting.

Solution: Create a custom function

To generate ordinal numbers efficiently, you can create a custom function:

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

    string number = num.ToString();
    int lastDigit = num % 10;
    int lastTwoDigits = num % 100;

    if (lastTwoDigits >= 11 && lastTwoDigits <= 13)
    {
        return number + "th";
    }
    else if (lastDigit == 1)
    {
        return number + "st";
    }
    else if (lastDigit == 2)
    {
        return number + "nd";
    }
    else if (lastDigit == 3)
    {
        return number + "rd";
    }
    else
    {
        return number + "th";
    }
}</code>
Copy after login

Example usage:

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

Internationalization instructions:

This method is for English ordinal numbers. For internationalization, consider researching the specific ordinal formats for each language and adapting the function accordingly.

The above is the detailed content of How Can I Efficiently Create Ordinal Numbers (e.g., 1st, 2nd, 3rd) 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