Login


Converting Numbers to Ordinal Strings

By Jonathan Wood on 2/26/2011
Language: C#
Technology: .NET
Platform: Windows
License: CPOL
Views: 5,635
General Programming » Text Handling » General » Converting Numbers to Ordinal Strings

Introduction

Here's a simple routine that converts an integer to an ordinal string. For example, it converts the number 1 to "1st", 2 to "2nd", 3 to "3rd", and so on.

Looking at this another way, it converts a number to an adjective used to describe the ordinal position of that number.

The NumberToOrdinal() Method

Listing 1 shows my NumberToOrdinal() method.

This extremely simple routine uses a lookup table of ordinal suffixes (_numSuffixes) to find the entry that corresponds to the digit in the one's column from the number being converted. It does this by getting the remainder of the number divided by 10 and using the result as an index into the table.

This approach works for every number from 0 to infinity with the exception of the teens, which all use the "th" suffix. So a special check is added for numbers in the range of 11 to 19.

The method then appends the suffix to the number and returns the result.

Listing 1: The NumberToOrdinal() Method

protected string[] _numSuffixes = { "th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th" };

/// <summary>
/// Converts integers like 1, 2, and 3 to ordinal strings like 1st, 2nd, and 3rd.
/// </summary>
/// <param name="n">Number to convert</param>
public string NumberToOrdinal(int n)
{
    // Make exception for teens
    int i = (n % 100);
    int j = (i > 10 && i < 20) ? 0 : (n % 10);
    return String.Format("{0}{1}", n, _numSuffixes[j]);
}

Conclusion

This is probably the shortest article ever to be published on this site, but I saw someone ask on the Web about a good way to do this and I thought some people might find it useful.

End-User License

Use of this article and any related source code or other files is governed by the terms and conditions of The Code Project Open License.

Author Information

Jonathan Wood

I'm a software/website developer working out of the greater Salt Lake City area in Utah. I've developed many websites including Black Belt Coder, Insider Articles, and others.

I hike each week with my dogs Suki and Sasha. You can see my hiking blog at Hiking Salt Lake.