NSInteger to NSString with spaces

Discussion in 'iOS Programming' started by nomar383, May 21, 2009.

  1. nomar383 macrumors 65816

    nomar383

    Joined:
    Jan 29, 2008
    Location:
    Rexburg, ID
    #1
    I humbly come before the macrumors programming gods with another inquiry :)

    Basically, I have an NSInteger that holds the score for the app I'm working on. It starts at 0 and can go up to 6 digits in length. I have it displaying in a UILabel (via a NSString obviously) and I need to put 2 spaces between each displayed digit. So it would display something like this:

    0 0 0 0 1 5

    I can get it to display the number just fine, no issue there. I'm just trying to wrap my head around putting 2 spaces between each individual digit. I think NSNumberFormatter may be of help, but I'm getting lost looking at the documentation for it. Any help/advice?

    EDIT: I also need to display leading zeros if possible
     
  2. kainjow Moderator emeritus

    kainjow

    Joined:
    Jun 15, 2000
    #2
    This should do what you want:
    Code:
    NSInteger num = 15;
    NSMutableString *str = [NSMutableString stringWithFormat:@"%06d", num];
    for (NSInteger i=1; i<[str length]; i+=2)
        [str insertString:@" " atIndex:i];
    The %06d part is how you pad it with zeros.
     
  3. nomar383 thread starter macrumors 65816

    nomar383

    Joined:
    Jan 29, 2008
    Location:
    Rexburg, ID

Share This Page