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

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


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!"


The solution is immediately available from NSNumberFormatter:

- (NSString *)getOrdinalStringFromInteger:(NSInteger)integer{    NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];    [formatter setLocale:[NSLocale currentLocale]];    [formatter setNumberStyle:NSNumberFormatterOrdinalStyle];    return [formatter stringFromNumber:[NSNumber numberWithInteger:integer]];}


You could use ICU, which includes a way of doing what you describe:

http://icu-project.org/apiref/icu4c/classRuleBasedNumberFormat.html

You don't say what context you're using Objective-C in, but if you're writing for Cocoa, ICU is actually present. However, reaching down to talk to it directly can be a bit tricky.

[edited to link to someone who actually seems to have figured out how to build ICU and link it]

How to build ICU so I can use it in an iPhone app?