如何在格式化NSNumber对象时指定小数位? [英] How to specify decimal places when formatting NSNumber objects?

查看:1618
本文介绍了如何在格式化NSNumber对象时指定小数位?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用下面的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"];

请参阅数字格式字符串语法(Mac OS X版本10.0至10.3)

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

Or you can use a 10.4 formatter with - setMinimumFractionDigits: and - setMaximumFractionDigits: with both set to 2.

这篇关于如何在格式化NSNumber对象时指定小数位?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆