使用NSNumberFormatter将数字转换为格式

时间:2014-11-27 10:40:49

标签: ios number-formatting nsnumberformatter

如何使用NSNumberFormatter将数字转换为4273095782到数字4 273 095 782?

我使用这个二极管但没有得到它

NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
formatter.numberStyle = kCFNumberFormatterDecimalStyle;
formatter.maximumIntegerDigits = 3;
formatter.minimumFractionDigits = 3;
formatter.groupingSeparator = @" ";
formatter.decimalSeparator = @" ";
NSString *formattedNumber = [formatter stringFromNumber:p];

2 个答案:

答案 0 :(得分:1)

您需要使用两个属性:setGroupingSize:表示最后3位数字,setSecondaryGroupingSize:表示所有其他数字:

完整的实施将如下:

NSInteger integer = 4273095782;
NSNumberFormatter * formatter = [NSNumberFormatter new];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
[formatter setGroupingSize:3];
[formatter setSecondaryGroupingSize:3];
[formatter setGroupingSeparator:@" "];
NSString * threeSeparated =  [formatter stringFromNumber:@(integer)];
NSLog(@"threeSeparated: %@", threeSeparated);

输出:4 273 095 782

答案 1 :(得分:0)

尝试这个小操作:

NSNumber *p = [NSNumber numberWithInt:123456789];

NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
formatter.numberStyle = kCFNumberFormatterDecimalStyle;
//     formatter.maximumIntegerDigits = 10;
//     formatter.minimumFractionDigits = 3;
formatter.groupingSeparator = @" ";
formatter.decimalSeparator = @" ";
NSString *formattedNumber = [formatter stringFromNumber:p];

NSLog(@"Formatted:%@", formattedNumber);

希望这会对你有所帮助。在这种情况下,您不需要限制整数位数:)

结果应为:2014-11-27 11:49:39.855 NSNumberFormatter[2399:789883] Formatted:123 456 789