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

前端 未结 20 1309
粉色の甜心
粉色の甜心 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条回答
  •  天涯浪人
    2020-12-03 01:43

    - (NSString *) formatOrdinalNumber:(NSInteger )number{
        NSString *result = nil;
        //0 remains just 0
        if (number == 0) {
            result = @"0";
        }
    
        //test for number between 3 and 21 as they follow a
        //slightly different rule and all end with th
        else if (number > 3 && number < 21)
        {
            result = [NSString stringWithFormat:@"%ld th",(long)number];
        }
        else {
            //return the last digit of the number e.g. 102 is 2
            NSInteger lastdigit = number % 10;
            switch (lastdigit)
            {
                case 1: result = [NSString stringWithFormat:@"%ld st",(long)number]; break;
                case 2: result = [NSString stringWithFormat:@"%ld nd",(long)number]; break;
                case 3: result = [NSString stringWithFormat:@"%ld rd",(long)number]; break;
                default: result = [NSString stringWithFormat:@"%ld th",(long)number];
            }
        }
        return result;
    }
    

提交回复
热议问题