NSNumberFormatter thousand separator and trailing zeros

人盡茶涼 提交于 2019-12-13 10:43:26

问题


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 NSNumbers. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!