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