开发者

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.


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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜