Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unexpected result from "stringWithFormat:"

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.

like image 359
Joe Smith Avatar asked Aug 09 '26 18:08

Joe Smith


1 Answers

@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.

[... stringWithFormat:@"%+.2d", 1]; // Result is @"+01"
[... stringWithFormat:@"%.2d", -1]; // Result is @"-01"
like image 67
EmptyStack Avatar answered Aug 11 '26 09:08

EmptyStack



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!