NSNumberFormatter and 'th' 'st' 'nd' 'rd' (ordinal) number endings

前端 未结 20 1267
粉色の甜心
粉色の甜心 2020-12-03 00:38

Is there a way to use NSNumberFormatter to get the \'th\' \'st\' \'nd\' \'rd\' number endings?

EDIT:

Looks like it does not exist. Here\'s what I\'m using.

20条回答
  •  萌比男神i
    2020-12-03 01:22

    Just adding another implementation as a class method. I didn't see this question posted until after I implemented this from an example in php.

    + (NSString *)buildRankString:(NSNumber *)rank
    {
        NSString *suffix = nil;
        int rankInt = [rank intValue];
        int ones = rankInt % 10;
        int tens = floor(rankInt / 10);
        tens = tens % 10;
        if (tens == 1) {
            suffix = @"th";
        } else {
            switch (ones) {
                case 1 : suffix = @"st"; break;
                case 2 : suffix = @"nd"; break;
                case 3 : suffix = @"rd"; break;
                default : suffix = @"th";
            }
        }
        NSString *rankString = [NSString stringWithFormat:@"%@%@", rank, suffix];
        return rankString;
    }
    

提交回复
热议问题