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>
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>
Note:
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!