Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
321 views
in Technique[技术] by (71.8m points)

ios - NSNumberformatter add extra zero

I'm looking for a way to display "1" as "01", so basically everything below 10 should have a leading 0.

What would be the best way to do this? I know I can just use a simple if structure to do this check, but this should be possible with NSNumberformatter right?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you just want an NSString, you can simply do this:

NSString *myNumber = [NSString stringWithFormat:@"%02d", number];

The %02d is from C. %nd means there must be at least n characters in the string and if there are less, pad it with 0's. Here's an example:

NSString *example = [NSString stringWithFormat:@"%010d", number];

If the number variable only was two digits long, it would be prefixed by eight zeroes. If it was 9 digits long, it would be prefixed by a single zero.

If you want to use NSNumberFormatter, you could do this:

NSNumberFormatter * numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setPaddingPosition:NSNumberFormatterPadBeforePrefix];
[numberFormatter setPaddingCharacter:@"0"];
[numberFormatter setMinimumIntegerDigits:10];
NSNumber *number = [NSNumber numberWithInt:numberVariableHere];

----UPDATE------ I think this solves your problem:

[_minutes addObject:[NSNumber numberWithInt:i]];
return [NSString stringWithFormat:@"%02d", [[_minutes objectAtIndex:row] intValue]]; 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...