问题描述
我使用下面的Objective-C代码来格式化一个NSNumber,它在大多数时候都可以正常工作,但是当NSNumber对象保存一个整数(没有小数部分)。
I'm using the following piece of Objective-C code to format a NSNumber, and it works fine most of the time, but it doesn't quite do what I want when the NSNumber object holds an integer (no fractional part).
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,它将显示55.23,因为它应该在我的 UILabel
。但是如果同一个变量持有55,它只会在标签上显示55。
So for instance, if self.totalFileSize
holds 55.2300, it will display "55.23" as it should on my UILabel
. But if that same variable holds 55, it will simply display "55" on the label.
我真正想要的是这个代码总是包含2个小数位输出。
What I really want is for this code to always include the 2 decimal places in the output.
如何实现?
推荐答案
格式字符串应该对于您希望始终存在的每个小数位有一个 0
。
Your format string should have a "0
" for each decimal place you want to always exist.
[formatter setFormat:@"###.00"];
[formatter setFormat:@"##0.00"];
请参阅
或者,您可以使用10.4格式化程序与和,两者都设置为2。
Or you can use a 10.4 formatter with - setMinimumFractionDigits: and - setMaximumFractionDigits: with both set to 2.
这篇关于如何在格式化NSNumber对象时指定小数位?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!