Search code examples
c++numberstostringordinals

Function for getting the ordinal of a number?


I was about to write a C++ function doing the following:

1 ---> "1st"
2 ---> "1nd"
3 ---> "3rd"
...
17657 --> "17657th"
...

i.e. produces the ordinal extension string for that number (it doesn't have to do an itoa() of the number itself). But then I thought "surely something in the standard library or boost does this already?"

Notes:

  • I know it's not hard to write this, there's an implementation in Python right here on SO, I just don't want to duplicate code.
  • I need this in English, obviously. A multi-language version would be nice for political-correctness considerations, not more than that...

Solution

  • Here's what I ended up writing:

    const char* ordinal_suffix(int n)
    {
            static const char suffixes [][3] = {"th", "st", "nd", "rd"};
            auto ord = n % 100;
            if (ord / 10 == 1) { ord = 0; }
            ord = ord % 10;
            if (ord > 3) { ord = 0; }
            return suffixes[ord];
    }
    

    The code golf solutions are cute, but - they really do optimize for terseness, not anything else. This is faster (although it could be made even faster by putting the suffixes in a .cpp out of the function body and making the code inlinable), much clearer, and still more terse than most other answers here.