views:

50

answers:

1

Is there a Objective-c function to return a NSString * from a NSUInteger, i.e.:

  • 1 -> 1st
  • 2 -> 2nd
  • ...
  • 10 -> 10th
  • 21 -> 21st
  • ...
  • 31 -> 31st

for the range from 1 to 31. Thanks!

+2  A: 
- (NSString *)stringFromInt:(int)num {
    NSString stringAddition;
    if (num >= 11 && num <= 13) {
        strinAddition = @"th";
    }
    else {
        switch (num % 10) {
            case 1: stringAddition = @"st"; break;
            case 2: stringAddition = @"nd"; break;
            case 3: stringAddition = @"rd"; break;
            default: stringAddition = @"th"; break;
        }
    }
    return [NSString stringWithFormat:@"%i%@", num, stringAddition];
}

EDIT:
Fixed the 11, 12, 13 issue.

Michael Kessler
What about `11`, `12`, `13`?
polygenelubricants
You call returning "11st" working? "12nd"? "13rd"? "31st" is good, but "11st" is pure breakage. Those special cases probably deserve their own `if()` statement, if you're really going to cover all your bases. Also I'd much rather this method be called maybe "ordinalFromInt", rather than "stringFromInt"--that name doesn't tell me we're adding anything, I'd expect it to be shorthand for `[NSString stringWithFormat:@"%d", num]`.
Dan Ray
You need just a bit more, just above the return: `if(num >= 11 `.
Chris Burt-Brown
Thank you for your comments. I have edited my answer...
Michael Kessler
Design-wise, code like this would probably fit best in an NSNumberFormatter subclass.
Mike Abdullah