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.
+(NSString*)ordinalNumberFormat:(NSInteger)num{ NSString *ending; int ones = num % 10; int tens = floor(num / 10); tens = tens % 10; if(tens == 1){ ending = @"th"; }else { switch (ones) { case 1: ending = @"st"; break; case 2: ending = @"nd"; break; case 3: ending = @"rd"; break; default: ending = @"th"; break; } } return [NSString stringWithFormat:@"%d%@", num, ending]; }
Adapted from nickf's answer here Is there an easy way in .NET to get "st", "nd", "rd" and "th" endings for numbers?
When writing ordinal numbers such as 1st, 2nd, 3rd, etc. you should use the last two letters on the word as it would be if you wrote out the whole word. Below are the ordinal numbers both written out and with digits for 1-20. As you can see, 1st, 2nd, and 3rd use -st, -nd, and -rd, but 4th-20th use -th.
(Background: numbers that have the additional letters, like st, nd, rd, and th are called ordinals: 1st, 2nd, 3rd, and 4th. When you shrink the letters and elevate them, they're called superscript ordinals: 1st, 2nd, 3rd, and 4th.)
The adjective terms which are used to denote the order of something/someone are 1st – First, 2nd-Second, 3rd-Third, 4th-Fourth, 5th-Fifth, 6th-Sixth, and so on. All these terms represent the ordinal numbers. Whereas the counting numbers are called cardinal numbers, such as 0, 1, 2, 3, 4, 5, etc.
The correct way to do this from iOS 9 onwards, is:
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init]; numberFormatter.numberStyle = NSNumberFormatterOrdinalStyle; NSLog(@"%@", [numberFormatter stringFromNumber:@(1)]); // 1st NSLog(@"%@", [numberFormatter stringFromNumber:@(2)]); // 2nd NSLog(@"%@", [numberFormatter stringFromNumber:@(3)]); // 3rd, etc.
Alternatively:
NSLog(@"%@", [NSString localizedStringFromNumber:@(1) numberStyle:NSNumberFormatterOrdinalStyle]); // 1st
This does the trick in one method (for English). Thanks nickf https://stackoverflow.com/a/69284/1208690 for original code in PHP, I just adapted it to objective C
:-
-(NSString *) addSuffixToNumber:(int) number { NSString *suffix; int ones = number % 10; int tens = (number/10) % 10; if (tens ==1) { suffix = @"th"; } else if (ones ==1){ suffix = @"st"; } else if (ones ==2){ suffix = @"nd"; } else if (ones ==3){ suffix = @"rd"; } else { suffix = @"th"; } NSString * completeAsString = [NSString stringWithFormat:@"%d%@", number, suffix]; return completeAsString; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With