“stringWithFormat:”出现意外结果

发布于 2024-12-07 12:34:18 字数 565 浏览 1 评论 0原文

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

int intValue = 1;
NSString *string = [NSString stringWithFormat:@"%+02d", intValue];

我以为字符串的值是“+01”,结果是“+1”。不知何故,格式字符串“+01”中的“0”被忽略。将代码更改为:

int intValue = 1;
NSString *string = [NSString stringWithFormat:@"%02d", intValue];

字符串的值现在为“01”。它确实生成前导“0”。但是,如果 intValue 为负数,如下所示:

int intValue = -1;
NSString *string = [NSString stringWithFormat:@"%02d", intValue];

string 的值变为“-1”,而不是“-01”。

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

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

趁年轻赶紧闹 2024-12-14 12:34:19

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

[... stringWithFormat:@"%+.2d", 1]; // Result is @"+01"
[... stringWithFormat:@"%.2d", -1]; // Result is @"-01"

@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"
爱本泡沫多脆弱 2024-12-14 12:34:19
NSString *string = [NSString stringWithFormat:@"+0%d", intValue];
NSString *string = [NSString stringWithFormat:@"-0%d", intValue];
NSString *string = [NSString stringWithFormat:@"+0%d", intValue];
NSString *string = [NSString stringWithFormat:@"-0%d", intValue];
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文