我使用以下代码通过添加千个分隔点来格式化字符串数字:
NSDecimalNumber *decimalNumber = [NSDecimalNumber decimalNumberWithString:@"0.000"];
NSLog(@"decimalNumber = %@",decimalNumber);
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setGroupingSeparator:@"."];
[numberFormatter setGroupingSize:3];
[numberFormatter setUsesGroupingSeparator:YES];
[numberFormatter setDecimalSeparator:@","];
[numberFormatter setMaximumFractionDigits:9];
NSString *finalString = [numberFormatter stringFromNumber:decimalNumber];
NSLog(@"finalString = %@",finalString);
如果我想格式化 @“0.000”字符串(不必是3个零,可以有更少或更多)我有以下日志输出:
decimalNumber = 0
finalString = 0
但我想要的是保持分数零,即在这种情况下我的字符串必须保持不变。当我创建NSDecimalNumber
时,我发现这些零丢失,我需要另一种方法。可能是什么?
答案 0 :(得分:4)
添加:
[numberFormatter setMinimumFractionDigits:3];
答案 1 :(得分:2)
Caleb的回答帮助我解决了这个问题,我想分享一下我是如何完全修复的:
1.首先我添加了这个方法:
- (uint) fractionalNumberCountFromString:(NSString*) numberString
{
NSRange fractionalPointRange = [numberString rangeOfString:@"."];
if (fractionalPointRange.location == NSNotFound)
{
return 0;
}
return numberString.length-fractionalPointRange.location-1;
}
2.第二,我添加了这一行,我设置NSNumberFormatter
:
[numberFormatter setMinimumFractionDigits:[self fractionalNumberCountFromString:@"0.000"]];
答案 2 :(得分:1)
试试这种方式
NSLocale *usLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"US"];
NSNumberFormatter *formatterN = [[NSNumberFormatter alloc] init];
[formatterN setMaximumFractionDigits:3];
[formatterN setMinimumFractionDigits:3];
[formatterN setLocale:usLocale];
[formatterN stringFromNumber:decimalNumber];