public
Last active

NSString category that returns an NSNumber with the correct ordinal ending. This was borrowed from http://stackoverflow.com/questions/3312935/nsnumberformatter-and-th-st-nd-rd-ordinal-number-endings

  • Download Gist
NSString+Additions.h
Objective-C
1 2 3 4 5
#import <Foundation/Foundation.h>
 
@interface NSString (Additions)
+ (NSString*)ordinalNumberFormat:(NSNumber *)numObj;
@end
NSString+Additions.m
Objective-C
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
#import "NSString+Additions.h"
 
@implementation NSString (Additions)
 
+ (NSString*)ordinalNumberFormat:(NSNumber *)numObj {
NSString *ending;
NSInteger num = [numObj integerValue];
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];
}
 
@end

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.