NSNumberFormatter千位分隔符和尾随零

时间:2014-08-22 09:09:02

标签: ios objective-c nsnumberformatter

我的帐户数组中有一个对象,值为8500.00。我想将其显示为8,500.00但是当我尝试这样做并打印到控制台时它返回null。有什么想法吗?

App Delegate

NSArray *balance        = [[NSArray alloc] initWithObjects:@"120.50", @"8500.00", nil];

//查看控制器

// Setup number formatter
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];

NSNumber *balance = [[appDelegate.accounts objectForKey:@"Available Balance"] objectAtIndex:indexPath.row];
NSLog(@"%@", balance); // Prints 8500.00

NSLog(@"%@", [formatter stringFromNumber:balance]); // Prints null

1 个答案:

答案 0 :(得分:1)

数组余额是NSString NOT NSNumber的数组。这就是方法stringFromNumber:返回nil的原因。

以下示例正常工作:

NSArray *balanceArr =@[@(120.50), @(8500.00)];
NSNumberFormatter *formatter = [NSNumberFormatter new];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
[formatter setMinimumFractionDigits:2];
[formatter setGroupingSize:3];
[formatter setGroupingSeparator:@"'"];
for (NSNumber *balance in balanceArr) {
    NSLog(@"Straight printing: %@", balance);
    NSLog(@"NumberFormatter: %@", [formatter stringFromNumber:balance]);
}

输出:

2014-08-22 12:18:16.669 dsghdtu[5343:60b] Straight printing: 120.5
2014-08-22 12:18:16.671 dsghdtu[5343:60b] NumberFormatter: 120.50
2014-08-22 12:18:16.671 dsghdtu[5343:60b] Straight printing: 8500
2014-08-22 12:18:16.672 dsghdtu[5343:60b] NumberFormatter: 8'500.00