Skip to content

Instantly share code, notes, and snippets.

@rgerard
Created July 16, 2012 00:40
Show Gist options
  • Save rgerard/3119444 to your computer and use it in GitHub Desktop.
Save rgerard/3119444 to your computer and use it in GitHub Desktop.
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
#import <Foundation/Foundation.h>
@interface NSString (Additions)
+ (NSString*)ordinalNumberFormat:(NSNumber *)numObj;
@end
#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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment