我的应用程序需要以毫米为单位显示公制单位,并根据我所做的研究(例如http://physics.nist.gov/cuu/pdf/sp811.pdf),建议您在有5位数之前不要添加分组分隔符。这可能与NSNumberFormatter一起使用吗?我知道我可以测试该值并根据其大小启用/禁用分组但我宁愿使用NSNumberFormatter的相应配置(如果存在)。 (顺便说一下,我在Mac OS X上)所以例如:
3456应显示为3456 mm
10234应显示为10,234 mm(假设逗号是分组分隔符)
我已阅读Apple文档并且没有看到任何内容。我尝试了不同的搜索,以便在Stackoverflow上找到答案,但找不到类似的问题。
以下是我目前正在设置NSNumberFormatter的方法:
if (numberFormatter == nil) {
numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setRoundingMode:NSNumberFormatterRoundHalfUp];
[numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
[numberFormatter setLocale:[NSLocale currentLocale]];
[numberFormatter setMinimumFractionDigits:0];
[numberFormatter setMaximumFractionDigits:2];
}
NSNumber *numberInMM = [NSNumber numberWithFloat:fLenInMMs];
NSString *numberStr = [numberFormatter stringFromNumber:numberInMM];
numberStr = [numberStr stringByAppendingString:@" mm"];
答案 0 :(得分:0)
long long d = fLenInMMs;
if (d>9999) {
NSNumberFormatter *numberFormatter=nil;
if (numberFormatter == nil) {
numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setRoundingMode:NSNumberFormatterRoundHalfUp];
[numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
[numberFormatter setLocale:[NSLocale currentLocale]];
[numberFormatter setMinimumFractionDigits:0];
[numberFormatter setMaximumFractionDigits:2];
}
NSNumber *numberInMM = [NSNumber numberWithFloat:fLenInMMs];
NSString *numberStr = [numberFormatter stringFromNumber:numberInMM];
numberStr = [numberStr stringByAppendingString:@" mm"];
NSLog(@"%@", numberStr);
}
else {
NSNumber *numberInMM = [NSNumber numberWithFloat:fLenInMMs];
NSString *numberStr = [NSString stringWithFormat:@"%@ mm",numberInMM];
}
编辑
您也可以继承NSNumberFormatter
并实施
- (NSString *)stringFromNumber:(NSNumber *)number
{
NSNumber *nm = [NSNumber numberWithInt:9999];
if (NSOrderedAscending==[number compare:nm]) {
return [NSString stringWithFormat:@"%@ mm",number];
}
return [super stringFromNumber:number];
}