Monday, April 5, 2010

Ordinal numbers

Ever want TeX to write an ordinal number correctly? There are a number of fairly complicated solutions on the web so I decided to write one that was easy to read and follow.
                \divide\count0 by100
                \multiply\count0 by100
                \advance\count@ by-\count0
                \divide\count0 by10
                \multiply\count0 by10
                \advance\count@ by-\count0
        \ifcase\count@ th%
                \or st%
                \or nd%
                \or rd%
                \else th%
Note that this requires @ to be a letter, so \makeatletter or \catcode`@11. The first \ifnum block mods out by 100 since that plays no role in determining the ordinal suffix. The next block mods out by 10 if \count@ is at least 20. This is because 10th through 19th use th but 20th through 99th only examine the ones digit. Lastly, if the one's digit is 0, 4, 5, 6, 7, 8, or 9, (or the tens digit is 1) use th, otherwise use st, nd, or rd as appropriate. Using old-style superscripts requires a trivial modification.

No comments:

Post a Comment