Joe Smith
Joe Smith

Reputation: 1920

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.

Upvotes: 3

Views: 926

Answers (2)

EmptyStack
EmptyStack

Reputation: 51374

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

Upvotes: 8

leena
leena

Reputation: 699

NSString *string = [NSString stringWithFormat:@"+0%d", intValue];
NSString *string = [NSString stringWithFormat:@"-0%d", intValue];

Upvotes: -1

Related Questions