【问题标题】:Unexpected result from "stringWithFormat:"“stringWithFormat:”的意外结果
【发布时间】:2011-10-01 05:43:39
【问题描述】:

以下 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];

字符串的值变成“-1”,而不是“-01”。

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

【问题讨论】:

  • 我怀疑这个数字给出了包括符号在内的字段宽度,而不是位数。
  • @Mark,你是对的。谢谢。
  • @Mark Byers,+1 评论!你是对的!

标签: iphone objective-c ios nsstring


【解决方案1】:

@Mark Byers 在他的评论中是正确的。相对于符号'+/-',指定'0''0' 填充有效数字。代替'0' 使用点'.''0' 填充有效数字无论符号如何

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

【讨论】:

    【解决方案2】:
    NSString *string = [NSString stringWithFormat:@"+0%d", intValue];
    NSString *string = [NSString stringWithFormat:@"-0%d", intValue];
    

    【讨论】:

    • intValue-1 时,第一行将导致+0-1。当intValue1 时,第二行将导致-01
    • 因此您可以使用 if 条件检查值是否小于 0 或大于 0 简单。
    • 好的。问题不在于在数字前添加额外的 0。如果实际数字小于 2 位,则用 0 填充数字;-)
    猜你喜欢
    • 2012-02-07
    • 2011-09-15
    • 2012-04-02
    • 2019-05-14
    • 2017-07-11
    • 2011-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多