I am taking the length of a nsstring and converting it to nsstring. I need this last string always 2 digits long, so for example word "hello"'s length in string would be "05" and not "5".
My code so far:
NSString *sth=@"hello";
NSMutableString *result=[NSString stringWithFormat:@"%d", sth.length]; //string is "5" and not "05" that i need
Add .2 after % sign(similar as with floating numbers and decimal part).
NSString *sth=@"hello";
NSMutableString *result=[NSString stringWithFormat:@"%.2d", sth.length];
Here is a simple way if I understand your question correctly:
NSString *fish = @"Chips";
NSString *length = [NSString stringWithFormat:@"%02d",[fish length]];
NSLog(@"Chips length is %@",length);
Produces:
2012-01-23 10:42:20.316 TestApp[222:707] Chips length is 05
The 02 means zero pad to length of 2. You will probably want to check that the length of your string is less than 99 characters though.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With