0

I am trying to find a solution to add zeros in the beginning of the number as per the total input provided.

Example: Number = 100 Total Number of digits = 3

The kind of format i will like to have is 001,002,003 and so on.

Thanks

I found out the solution for the same. Posting it below:

 while (totalNumCopy) {
        totalNumCopy = totalNumCopy/10;
        noOfDigits++;
    }

    NSMutableString *thumbName = nil;
    if(noOfDigits > 0)
    {
        NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
        [formatter setFormatWidth:noOfDigits];
        [formatter setPaddingCharacter:@"0"];
        [formatter setNumberStyle: NSNumberFormatterPadBeforePrefix];
        NSString *stringNumber = [formatter stringFromNumber:[NSNumber numberWithInt:i+1]];
        thumbName = [NSString stringWithFormat:@"PageThumb%@.png",stringNumber];
        [formatter release];
    }

2 Answers 2

4

the basic string formatter is like this:

NSLog(@"%03d, %03d, %03d", 1, 2, 3);

the result would be:

001, 002, 003

maybe it helps on you.

3
  • The total number counted is dynamic. Its value is generated at runtime. So it can even have 4 digits also. I know this it can be done using the NSNumberFormatter. Just need some help on it that how to do it. Jul 30, 2012 at 9:12
  • what result do you expect exactly? please, re-define your question then.
    – holex
    Jul 30, 2012 at 9:16
  • I did fount out the solution for the same please check above. Thanks anyways for the help Jul 30, 2012 at 9:23
2
NSString *myNumber = [NSString stringWithFormat:@"%03d", number];

i think the above code will help you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.