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?
Remember internationalisation!
The solutions here only work for English. Things get a lot more complex if you need to support other languages.
For example, in Spanish "1st" would be written as "1.o", "1.a", "1.os" or "1.as" depending on whether the thing you're counting is masculine, feminine or plural!
So if your software needs to support different languages, try to avoid ordinals.
Another alternative that I used based on all the other suggestions, but requires no special casing:
Requested "less redundancy" version of samjudson's answer...
Based off the other answers:
I use this extension class:
While I haven't benchmarked this yet, you should be able to get better performance by avoiding all the conditional case statements.
This is java, but a port to C# is trivial:
Note, the reduction of conditionals and the use of the array lookup should speed up performance if generating a lot of ordinals in a tight loop. However, I also concede that this isn't as readable as the case statement solution.