4

Possible Duplicate:
NSNumberFormatter and ‘th’ ‘st’ ‘nd’ ‘rd’ (ordinal) number endings

Hello,

I'm building an application that downloads player ranks and displays them. So say for example, you're 3rd out of all the players, I inserted a condition that will display it as 3rd, not 3th and i did the same for 2nd and 1st. When getting to higher ranks though, such as 2883rd, it'll display 2883th (for obvious reasons)

My question is, how can I get it to reformat the number to XXX1st, XXX2nd, XXX3rd etc?

To show what I mean, here's how I format my number to add a "rd" if it's 3

if ([[container stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] isEqualToString:@"3"])
{
    NSString*badge = [NSString stringWithFormat:@"%@rd",[container stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]];
    NSString*scoreText = [NSString stringWithFormat:@"ROC Server Rank: %@rd",[container stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]];
    profile.badgeValue = badge;
    rank.text = scoreText;
}

I can't do this for every number up to 2000 (there are 2000 ranks in total) - what can I do to solve this problem?

Community
  • 1
  • 1
Pripyat
  • 2,937
  • 2
  • 35
  • 69
  • 1
    What is the obvious reason for displaying the ordinal as 2883th ? When I read it I say 'two-thousand eight-hundred and eighty-third', rather than 'two-thousand eight-hundred and eighty-threeth'. – High Performance Mark Jul 23 '10 at 16:42
  • 1
    Already asked: http://stackoverflow.com/questions/3312935/nsnumberformatter-and-th-st-nd-rd-ordinal-number-endings – Kurbz Jul 23 '10 at 16:44
  • ...Why suddenly everyone wants to ordinalize a number recently? – kennytm Jul 23 '10 at 16:49

2 Answers2

2

Here's a short snippet in another language: http://www.bytechaser.com/en/functions/b6yhfyxh78/convert-number-to-ordinal-like-1st-2nd-in-c-sharp.aspx

/// <summary>
/// Create an ordinal number from any number 
/// e.g. 1 becomes 1st and 22 becomes 22nd
/// </summary>
/// <param name="number">Number to convert</param>
/// <returns>Ordinal value as string</returns>
public static string FormatOrdinalNumber(int number)
{
    //0 remains just 0
    if (number == 0) return "0";
    //test for number between 3 and 21 as they follow a 
    //slightly different rule and all end with th            
    if (number > 3 && number < 21)
    {
        return number + "th";
    }
    //return the last digit of the number e.g. 102 is 2
    var lastdigit = number % 10;
    //append the correct ordinal val
    switch (lastdigit)
    {
        case 1: return number + "st";
        case 2: return number + "nd";
        case 3: return number + "rd";
        default: return number + "th";
    }
}
Kurbz
  • 11,003
  • 2
  • 17
  • 12
1

Make it check the last digit of every number then add the suffix accordingly.

Checking the last 2 digits will fix it.

David Skrundz
  • 13,067
  • 6
  • 42
  • 66