问题
I have an object in my account array with a value of 8500.00. I'd like to display that as 8,500.00 but when I try to do so and print to the console it returns null. Any ideas?
App Delegate
NSArray *balance = [[NSArray alloc] initWithObjects:@"120.50", @"8500.00", nil];
// View controller
// 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:
An array balance is an array of NSString
NOT NSNumber
s. That's why method stringFromNumber:
returns nil.
The following example works fine:
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]);
}
Output:
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
来源:https://stackoverflow.com/questions/25443387/nsnumberformatter-thousand-separator-and-trailing-zeros