objective-c - 在格式化 float 以供显示时限制小数位数和总位数

标签 objective-c cocoa-touch nsnumberformatter decimal-point

我需要在有限宽度的区域中最有效地打印浮点值。我正在使用 NSNumberFormatter,我将小数点后的两个数字设置为默认值,这样当我有一个像 234.25 这样的数字时,它会按原样打印:234.25。但是当我有 1234.25 时,我希望它打印为:1234.3,并且 11234.25 应该打印为 11234

我需要在小数点后最多两位数,如果我在小数点后有数字,总共最多需要五位数字,但如果整数部分有更多数字,它也应该打印多于五位数字。

我看不到可以限制 NSNumberFormatter 中的总位数。这是否意味着我应该编写自己的函数以这种方式格式化数字?如果是这样,那么获取数字的整数和小数部分的位数的正确方法是什么?我也更喜欢使用 CGFLoat,而不是 NSNumber,以避免额外的类型转换。

最佳答案

您正在寻找“最大有效数字”和“最大小数位数”的组合,以及特定的舍入行为。 NSNumberFormatter 等于任务:

float twofortythreetwentyfive = 234.25;
float onetwothreefourtwentyfive = 1234.25;
float eleventwothreefourtwentyfive = 11234.25;

NSNumberFormatter * formatter =  [[NSNumberFormatter alloc] init];
[formatter setUsesSignificantDigits:YES];
[formatter setMaximumSignificantDigits:5];
[formatter setMaximumFractionDigits:2];
[formatter setRoundingMode:NSNumberFormatterRoundCeiling];

NSLog(@"%@", [formatter stringFromNumber:[NSNumber numberWithFloat:twofortythreetwentyfive]]);
NSLog(@"%@", [formatter stringFromNumber:[NSNumber numberWithFloat:onetwothreefourtwentyfive]]);
NSLog(@"%@", [formatter stringFromNumber:[NSNumber numberWithFloat:eleventwothreefourtwentyfive]]);

结果:

2012-04-26 16:32:04.481 SignificantDigits[11565:707] 234.25
2012-04-26 16:32:04.482 SignificantDigits[11565:707] 1234.3
2012-04-26 16:32:04.483 SignificantDigits[11565:707] 11235

关于objective-c - 在格式化 float 以供显示时限制小数位数和总位数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10337171/

相关文章:

ios - 类型 MyViewController 不符合协议(protocol) 'STPPaymentContextDelegate'

ios - Quickblox:体系结构 x86_64 的 undefined symbol :错误

ios - 为什么 Apple 的 SimpleTextInput 示例代码效率低下

objective-c - NSNumberFormatter 停止缩短数字

iphone - iOS 4 升级后 UITableView 的滚动性能出现抖动

ios - 将私钥添加到 iOS Keychain

ios - MKMapView 或 CLLocationManger - 确定用户的当前位置

ios - UITableView 没有重新加载

swift - 大于或等于一千万的数字,使用 NumberFormatter Precision

ios - NumberFormatter 参数标签 '(_:)' 不匹配任何可用的重载