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

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

Mary-Kate Olsen
Release: 2025-01-14 16:36:44
Original
191 people have browsed it

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

Creating ordinal numbers in C#

In C#, creating ordinal numbers (for example, "1st", "2nd", and "3rd") from numerical values ​​is a common task. This can be achieved through custom functions.

Function to create ordinal numbers

Given that String.Format() does not provide an out-of-the-box ordinal creation solution, a custom function can be used:

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

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

This function checks the last two digits of the input number and applies the appropriate suffix.

Usage:

The AddOrdinal function is used as follows:

<code class="language-csharp">string ordinal = AddOrdinal(1);
Console.WriteLine(ordinal); // 1st</code>
Copy after login

Notes on internationalization:

It is important to note that this function is not internationalized, which means the output will be based on English language conventions. To support multiple languages, additional logic is needed to handle the different rules for creating ordinal numbers.

The above is the detailed content of How Can I Create 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