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:
Here's what I ended up writing:
const char* ordinal_suffix(int n)
{
static const char suffixes [][3] = {"th", "st", "nd", "rd"};
int ord = n % 100;
if (ord / 10 == 1) { ord = 0; } // 11th ... 19th
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 perhaps 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.
Notes:
xth()
or even just th()
.long long int
and implicit conversion.n
is negative, but it's not obvious what the ordinal suffix should be for negative numbers; and the result for negative n
's will probably not be what you would expect.