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

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

Barbara Streisand
Barbara StreisandOriginal
2025-01-14 16:42:48919browse

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

Generating Ordinal Numbers in C#

C# doesn't offer a built-in function (like String.Format()) to directly create ordinal numbers (1st, 2nd, 3rd, etc.). However, a simple custom function provides a clean solution.

Here's a concise example:

<code class="language-csharp">public static string ToOrdinal(int num)
{
    if (num <= 0) return num.ToString();

    string suffix = "";
    int lastDigit = num % 10;
    int lastTwoDigits = num % 100;

    if (lastTwoDigits >= 11 && lastTwoDigits <= 13) suffix = "th";
    else if (lastDigit == 1) suffix = "st";
    else if (lastDigit == 2) suffix = "nd";
    else if (lastDigit == 3) suffix = "rd";
    else suffix = "th";

    return num + suffix;
}</code>

This function efficiently handles both positive and negative numbers. For positive numbers, it determines the correct ordinal suffix ("st", "nd", "rd", or "th") based on the last digit and last two digits. Negative numbers are returned unchanged as they don't have standard ordinal forms. Remember this function is specific to English ordinals; internationalization would require a more complex solution.

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

Statement:
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