Is there an easy way in C# to create Ordinals for a number? For example:
- 1 returns 1st
- 2 returns 2nd
- 3 returns 3rd
- ...etc
Can this be done through String.Format()
or are there any functions available to do this?
Is there an easy way in C# to create Ordinals for a number? For example:
Can this be done through String.Format()
or are there any functions available to do this?
EDIT: As YM_Industries points out in the comment, samjudson's answer DOES work for numbers over 1000, nickf's comment seems to have gone, and I can't remember what the problem I saw was. Left this answer here for the comparison timings.
An awful lot of these don't work for numbers > 999, as nickf pointed out in a comment (EDIT: now missing).
Here is a version based off a modified version of samjudson's accepted answer that does.
Also Shahzad Qureshi's answer using string manipulation works fine, however it does have a performance penalty. For generating a lot of these, a LINQPad example program makes the string version 6-7 times slower than this integer one (although you'd have to be generating a lot to notice).
LINQPad example:
Simple, clean, quick
Or better yet, as an extension method
Now you can just call
or even as direct as
FWIW, for MS-SQL, this expression will do the job. Keep the first WHEN (
WHEN num % 100 IN (11, 12, 13) THEN 'th'
) as the first one in the list, as this relies upon being tried before the others.For Excel :
The expression
(MOD(A1-11,100)>2)
is TRUE (1) for all numbers except any ending in11,12,13
(FALSE = 0). So2 * RIGHT(A1) * (MOD(A1-11,100)>2) +1)
ends up as 1 for 11/12/13, otherwise :1 evaluates to 3
2 to 5,
3 to 7
others : 9
- and the required 2 characters are selected from
"thstndrdth"
starting from that position.If you really want to convert that fairly directly to SQL, this worked for me for a handful of test values :
My version of Jesse's version of Stu's and samjudson's versions :)
Included unit test to show that the accepted answer is incorrect when number < 1
You'll have to roll your own. From the top of my head:
You can then do
Edited for 11/12/13 exceptions. I DID say from the top of my head :-)
Edited for 1011 -- others have fixed this already, just want to make sure others don't grab this incorrect version.