Why doesn't NSNumberFormatter remove the decimal point and trailing zeros?

scolfax picture scolfax · Apr 1, 2011 · Viewed 10.8k times · Source

I want to convert an unsigned long int to an NSString formatted with commas every 3 digits and neither a decimal point nor trailing zeros. I can get the commas into the NSString without any trouble using NSNumberFormatter, but for some reason I can't get the decimal point and zeros to go away.

This is my code:

NSNumberFormatter *fmtr;
unsigned long int intToBeDisplayed;
intToBeDisplayed = 1234567890;
fmtr = [[[NSNumberFormatter alloc] init] autorelease];
[fmtr setUsesGroupingSeparator:YES];
[fmtr setGroupingSeparator:@","];
[fmtr setGroupingSize:3];
[fmtr setAlwaysShowsDecimalSeparator:NO];
NSLog([fmtr stringFromNumber:[NSNumber numberWithUnsignedLong:intToBeDisplayed]]);

The log displays "1,234,567,890.00", appropriately adding the commas but also unfortunately the unwanted ".00". I've tried this construct with int instead of unsigned long int, with smaller integer values, and other constructs from various blogs all to no avail. I'd be very grateful for any suggestions on how to get the decimal point and trailing zeros out of the NSString.

I'm a newbie to Objective-C, becoming on oldbie with respect to the blurry-eyed syndrome trying to solve this problem, but am at that stage where every little lesson learned and success achieved in Objective-C is a source of great joy.

Answer

David Peckham picture David Peckham · Jul 5, 2011

You can also use setMaximumFractionDigits to truncate the fraction:

unsigned long int intToBeDisplayed = 1234567890;
NSNumber *longNumber = [NSNumber numberWithUnsignedLong:intToBeDisplayed];

NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setUsesGroupingSeparator:YES];
[formatter setGroupingSeparator:@","];
[formatter setGroupingSize:3];
[formatter setMaximumFractionDigits:0];

NSString *formattedNumber = [formatter stringFromNumber:longNumber];
NSLog(@"The formatted number is %@", formattedNumber);

Which results in:

The formatted number is 1,234,567,890

This works in iOS 2.0 and later.