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