Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
267 views
in Technique[技术] by (71.8m points)

ios - NSNumberFormatter thousand separator and trailing zeros

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...