“stringWithFormat:”出现意外结果
以下 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
@Mark Byers 他的评论是正确的。指定
'0'
会用'0'
填充相对于符号'+/-'
的有效数字。使用点'.'
代替'0'
,它用'0'
填充有效数字而不管符号。@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.