What would be the expected result from the following Objective C code?
int intValue = 1;
NSString *string = [NSString stringWithFormat:@"%+02d", intValue];
I thought the value of string would be “+01”, it turns out to be “+1”. Somehow “0” in format string “+01” is ignored. Change code to:
int intValue = 1;
NSString *string = [NSString stringWithFormat:@"%02d", intValue];
the value of string is now “01”. It does generate the leading “0”. However, if intValue is negative, as in:
int intValue = -1;
NSString *string = [NSString stringWithFormat:@"%02d", intValue];
the value of string becomes “-1”, not “-01”.
Did I miss anything? Or is this a known issue? What would be the recommended workaround?
Thanks in advance.
@Mark Byers is correct in his comment. Specifying
'0'pads the significant digits with'0'with respect to the sign'+/-'. Instead of'0'use dot'.'which pads the significant digits with'0'irrespective of the sign.