Title: Convert an integer into an ordinal (1st, 2nd, 3rd) in C#
This example uses the following int extension method to convert an integer into an ordinal. The method returns an integer's ordinal suffix, as in "rd" fo rthe value i1103, so you can make 1103rd or 1,103rd.
// Return the int's ordinal extension.
public static string ToOrdinal(this int value)
{
// Start with the most common extension.
string extension = "th";
// Examine the last 2 digits.
int last_digits = value % 100;
// If the last digits are 11, 12, or 13, use th. Otherwise:
if (last_digits < 11 || last_digits > 13)
{
// Check the last digit.
switch (last_digits % 10)
{
case 1:
extension = "st";
break;
case 2:
extension = "nd";
break;
case 3:
extension = "rd";
break;
}
}
return extension;
}
The code is fairly simple. The following table shows how the suffix depends on a number's final digits.
Number Ends In: |
Suffix |
11, 12, or 13 |
th |
1 |
st |
2 |
nd |
3 |
rd |
Everything else |
th |
The code simply checks the values in the table and returns the appropriate suffix.
The following code shows how the main program uses the extension method when the value in the TextBox changes.
// Display the ordinal version of the number.
private void txtNumber_TextChanged(object sender, EventArgs e)
{
// Parse the value and display its ordinal extension.
try
{
int value = int.Parse(txtNumber.Text,
System.Globalization.NumberStyles.Any);
txtResult.Text = value.ToString("#,##0 ") +
value.ToOrdinal();
}
catch
{
txtResult.Clear();
}
}
This code parses the text to get an integer value. It then displays the value followed by the result returned by the value's ToOrdinal method.
Download the example to experiment with it and to see additional details.
|