Home > Backend Development > C++ > How to Convert Numbers to Ordinal Forms (1st, 2nd, 3rd, etc.) in C#?

How to Convert Numbers to Ordinal Forms (1st, 2nd, 3rd, etc.) in C#?

Linda Hamilton
Release: 2025-01-14 16:26:43
Original
366 people have browsed it

How to Convert Numbers to Ordinal Forms (1st, 2nd, 3rd, etc.) in C#?

Number ordinal conversion in C#

In C#, the string formatting function does not directly support ordinal numbers. To convert a number into ordinal form, you need to use a custom function.

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

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

    if (lastDigit == 1 && lastTwoDigits != 11) suffix = "st";
    else if (lastDigit == 2 && lastTwoDigits != 12) suffix = "nd";
    else if (lastDigit == 3 && lastTwoDigits != 13) suffix = "rd";

    return num + suffix;
}</code>
Copy after login

This function handles ordinal numbers of numbers less than or equal to zero, and provides different suffixes for different cases (e.g., 1st, 2nd, 3rd, etc.).

Usage:

<code class="language-csharp">int num = 5;
string ordinalForm = AddOrdinal(num);
Console.WriteLine(ordinalForm); // 输出:5th</code>
Copy after login

Note:

  • Numbers less than or equal to zero have no ordinal number, so this function handles such cases accordingly.
  • This function is not internationalized, which means it only supports English ordinal forms.

The above is the detailed content of How to Convert Numbers to Ordinal Forms (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