我正在使用以下的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个小数位。
我怎样才能做到这一点?
答案 0 :(得分:16)
对于您希望始终存在的每个小数位,您的格式字符串应具有“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。
答案 1 :(得分:7)
我相信你要找的是:“%。2f”
最坏的情况是,您可以拆分该值,检查小数点后是否有任何内容。如果没有手动添加00?
答案 2 :(得分: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往往是一个性能损失,但这些是另一个线程的问题。