NSNumberFormatter and 'th' 'st' 'nd' 'rd' (ordinal) number endings

Viewed 24812

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?

21 Answers

You can try this, Its well simplified.

function numberToOrdinal(n) {

  if (n==0) {
    return n;
   }
   var j = n % 10,
       k = n % 100;


   if (j == 1 && k != 11) {
       return n + "st";
   }
   if (j == 2 && k != 12) {
       return n + "nd";
   }
   if (j == 3 && k != 13) {
       return n + "rd";
   }
   return n + "th";
}
public extension Int {
 var ordinalValue: String? {
    let formatter = NumberFormatter()
    formatter.numberStyle = .ordinal
    formatter.locale = Locale(identifier: "en_US")
    return formatter.string(from: NSNumber(value: self))
 }
}

Don't forget to add the Locale, if it is not added, it won't work. Usage:

let number = 2
let ordinalNumber = number.ordinalValue
print(ordinalNumber) //It will print 2nd
Related