Converting floats to a String with commas

Discussion in 'iPhone/iPad Programming' started by roeik, Jan 3, 2009.

  1. macrumors member

    Joined:
    Dec 25, 2008
    #1
    What's the best way to convert a any number to a string with commas?
    so for instance:

    int i = 1000000

    will be printed as 1,000,000

    thanks
     
  2. piz
    macrumors newbie

    Joined:
    Dec 30, 2008
    #2
    stringWithFormat

    Look for stringWithFormat.
     
  3. thread starter macrumors member

    Joined:
    Dec 25, 2008
    #3
    I did, but I can't find a comma notation there, only scientific notation.
     
  4. piz
    macrumors newbie

    Joined:
    Dec 30, 2008
    #4
    Since i use it seldom I cannot give you the entire info.
    But the following is outside from one of my running programs.
    The documentation under XCode Help is very good, as far as I remember.

    Code:
    [NSString localizedStringWithFormat:@"%1.1f%%", [[NSNumber numberWithFloat: 1011.213 ]
    
     
  5. macrumors 68030

    PhoneyDeveloper

    Joined:
    Sep 2, 2008
    #5
    Look at NSNumberFormatter.
     
  6. thread starter macrumors member

    Joined:
    Dec 25, 2008
    #6
    Just for other people who needs it, the specific command is:
    [numberFormatter setFormat:mad:"$#,##0.00"];

    (I added the $ sign to add the currency symbol).
     
  7. thread starter macrumors member

    Joined:
    Dec 25, 2008
    #7
    for some reason when running the app on the device you get an error message when using setFormat.
    Instead use:

    numberFormatter = [[NSNumberFormatter alloc] init];
    [numberFormatter setFormatterBehavior:NSNumberFormatterBehavior10_4];
    [numberFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
     

Share This Page