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

后端 未结 5 1649
悲哀的现实
悲哀的现实 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:35

    Have you taken a look at TTTOrdinalNumberFormatter which is in FormatterKit? It works great, and I'm pretty sure it's exactly what you're looking for.


    Here's an example taken from the kit:

    TTTOrdinalNumberFormatter *ordinalNumberFormatter = [[TTTOrdinalNumberFormatter alloc] init];
    [ordinalNumberFormatter setLocale:[NSLocale currentLocale]];
    [ordinalNumberFormatter setGrammaticalGender:TTTOrdinalNumberFormatterMaleGender];
    NSNumber *number = [NSNumber numberWithInteger:2];
    NSLog(@"%@", [NSString stringWithFormat:NSLocalizedString(@"You came in %@ place!", nil), [ordinalNumberFormatter stringFromNumber:number]]);
    

    Assuming you've provided localized strings for "You came in %@ place!", the output would be:

    * English: "You came in 2nd place!"
    * French: "Vous êtes venu à la 2eme place!"
    * Spanish: "Usted llegó en 2.o lugar!"
    

提交回复
热议问题