Objective-C: format numbers to ordinals: 1, 2, 3, .. to 1st, 2nd, 3rd

后端 未结 5 1644
悲哀的现实
悲哀的现实 2021-01-04 00:57

In Objective C, is there any way to format an integer to ordinals 1 => \"1st\", 2 => \"2nd\" etc... that works for any language? So if the user

5条回答
  •  失恋的感觉
    2021-01-04 01:40

    You need a rule set for each language you want to support. Any language is asking too much: they are all wildly different. First, create a rule set class which holds the regular and the exception cases for a given language. That class needs a single method that takes a number and returns a string suffix (or the number plus the suffix.) Create rule set instances (statically) for each language you care about.

    Then create a category on NSNumber that returns a suffix pulled from the appropriate rule set for whatever language the user needs (system locale, or some choice they make, or case by case.)

    Each language has different rules, of course. For example, English is relatively complicated: 1st, 2nd, 3rd, 4th, 5th, ... 20th and then it starts again at st, nd, rd, th... Unit 1s, 2s, 3s and 4s are always special cases. Zero is 'th' (zeroth, hundredth, millionth etc.)

    French is different. 1er, then it's x ième all the way up. (These are usually abbreviated to just 're' and 'e', making French quite easy.)

    Japanese gets very odd. Cardinal 1, 2, 3, 4: (ichi, ni, san, yon) becomes tsuichi, futsuka, mikka and yokka. Those aren't suffixes though: the numbers are named differently when they're used as ordinals. Luckily, because that's incredibly confusing, you can just stick a kanji 'kai' character (which looks like a box in box) after the number and everyone knows what you mean.

提交回复
热议问题