【问题标题】:How to specify decimal places when formatting NSNumber objects?格式化 NSNumber 对象时如何指定小数位?
【发布时间】:2009-02-08 00:15:59
【问题描述】:

我正在使用下面的 Objective-C 代码来格式化 NSNumber,它在大多数情况下都能正常工作,但是当 NSNumber 对象包含一个整数(没有小数部分)时,它并不能完全满足我的要求)。

UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(80.0f, 90.0f, 225.0f, 40.0f)];
label.backgroundColor = [UIColor clearColor];
label.textColor = [UIColor whiteColor];
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
[formatter setFormat:@"###.##"];
int bytes = 1024 * 1024;
NSNumber *total = [NSNumber numberWithFloat:([self.totalFileSize floatValue] / bytes)];
label.text = [NSString stringWithFormat:@"0.00 MB of %@ MB", [formatter stringFromNumber:total]];

因此,例如,如果self.totalFileSize 包含 55.2300,它将在我的UILabel 上显示“55.23”。但如果同一个变量包含 55,它只会在标签上显示“55”。

我真正想要的是此代码始终在输出中包含 2 位小数。

我怎样才能做到这一点?

【问题讨论】:

    标签: iphone cocoa cocoa-touch


    【解决方案1】:

    您的格式字符串应该有一个“0”来代表您希望始终存在的每个小数位。

    [formatter setFormat:@"###.00"];
    

    对于“55.23”、“.23”和“.20”

    [formatter setFormat:@"##0.00"];
    

    对于“55.23”和“0.23”和“0.20”

    Number Format String Syntax (Mac OS X Versions 10.0 to 10.3)

    或者您可以使用 10.4 格式化程序,将 - setMinimumFractionDigits:- setMaximumFractionDigits: 都设置为 2。

    【讨论】:

    • setFormat: 不适用于 iOS(可能在模拟器中有效,但在设备上无效)。您需要使用 setPositiveFormat: 和 setNegativeFormat:
    • 在 iOS 上您需要使用 setMinimumFractionDigits: 和/或 - setMaximumFractionDigits:
    【解决方案2】:

    我相信您正在寻找的是:“%.2f”

    最坏的情况,你可以拆分值,检查小数点后是否有任何内容。如果没有手动添加00?

    【讨论】:

    • 我相信你的意思你相信他正在寻找的是:"%.2f" ;)
    • 使用它不会做你认为的那样,因为将 NSNumber 对象传递给 NSLog 将导致它调用 [obj description],它返回一个字符串。在任何情况下,我都试图避免像“如果不存在则追加 00”这样的黑客攻击。我确定 NSNumberFormatter 有一个功能可以在这里做我想做的事情。
    • @Garret,我迫切希望找到这个简单的解决方案。数字格式化并不容易。谢谢。
    【解决方案3】:

    使用localizedStringWithFormat 可能会更好,就像这样...

    [UILabel alloc] initWithFrame:CGRectMake(80.0f, 90.0f, 225.0f, 40.0f)];
    label.backgroundColor = [UIColor clearColor];
    label.textColor = [UIColor whiteColor];
    int bytes = 1024 * 1024;
    label.text = [NSString localizedStringWithFormat:@"0.00 MB of %.2f MB", ([self.totalFileSize floatValue] / bytes)];
    

    当然,bytes 可能是 const unsigned,而 clearColor 往往会占用性能,但这些是另一个线程的问题。

    【讨论】:

    • 使用clearColor 有什么问题,什么会更好?非常感谢!
    • 感谢localizedStringWithFormat 的提示。我正在拼命寻找一种简单的方法来确保本地化小数分隔符。
    猜你喜欢
    • 1970-01-01
    • 2022-09-26
    • 1970-01-01
    • 2020-10-02
    • 2021-09-03
    • 1970-01-01
    • 1970-01-01
    • 2019-07-13
    • 2020-10-19
    相关资源
    最近更新 更多