"stringWithFormat:"的意外结果

Joe*_*ith 3 iphone objective-c nsstring ios

以下Objective C代码的预期结果是什么?

int intValue = 1;
NSString *string = [NSString stringWithFormat:@"%+02d", intValue];
Run Code Online (Sandbox Code Playgroud)

我认为字符串的值是"+01",结果是"+1".格式字符串"+01"中的某些"0"被忽略.将代码更改为:

int intValue = 1;
NSString *string = [NSString stringWithFormat:@"%02d", intValue];
Run Code Online (Sandbox Code Playgroud)

string的值现在是"01".它确实产生前导"0".但是,如果intValue为负数,则如下所示:

int intValue = -1;
NSString *string = [NSString stringWithFormat:@"%02d", intValue];
Run Code Online (Sandbox Code Playgroud)

string的值变为"-1",而不是"-01".

我错过了什么吗?或者这是一个已知的问题?推荐的解决方法是什么?提前致谢.

Emp*_*ack 8

@Mark Byers的评论是正确的.使用相对于符号指定'0'有效数字'0'的填充'+/-'.而不是'0'使用填充'.' 有效数字的点而'0' 不管符号.

[... stringWithFormat:@"%+.2d", 1]; // Result is @"+01"
[... stringWithFormat:@"%.2d", -1]; // Result is @"-01"
Run Code Online (Sandbox Code Playgroud)