Formatting Numbers – NSNumberFormatter Examples

Wed, Jun 16

The previous post on how to Get Total and Free Space on the Mounted File System is a good segue to this post, as the formatting of the output from the previous code example left a little to be desired, see the figure below.

Without delimiters to mark off thousands, it’s a little difficult to read. Welcome NSNumberFormatter, which provides a simple means to comma delimit NSNumber objects.

NSNumberFormatter and Thousands Separator

NSNumberFormatter includes a handful of pre-defined number format styles. The code below uses the decimal formatting style to provide the comma delimited format we are after:

// Get access to a file manager as our means
// to perform file operations
NSFileManager *fileManager = [NSFileManager defaultManager];
 
// Using the application home directory, get dictionary of attributes
NSDictionary *attributesDict = [fileManager attributesOfFileSystemForPath:NSHomeDirectory() error:NULL];
 
// Print total file system size and available space
NSLog(@"System size: %lld", [[attributesDict objectForKey:NSFileSystemSize] longLongValue]);
NSLog(@"System free space: %lld", [[attributesDict objectForKey:NSFileSystemFreeSize] longLongValue]);    
 
// Create formatter
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];  
 
//--------------------------------------------
// Set to decimal style and output to console
//--------------------------------------------
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
NSString *formattedOutput = [formatter stringFromNumber:[attributesDict objectForKey:NSFileSystemFreeSize]];
NSLog(@"System free space: %@", formattedOutput);

The output of the code above is now much more readable:

NSNumberFormatter and Currency

Here’s another example of a style, formatting the output as currency. Note in the example that I’ve also changed the locale to demonstrate how the formatter manages output based on this setting.

//--------------------------------------------
// Format style as currency, output to console
//--------------------------------------------
[formatter setNumberStyle:NSNumberFormatterCurrencyStyle];
formattedOutput = [formatter stringFromNumber:[attributesDict objectForKey:NSFileSystemFreeSize]];
NSLog(@"Output as currency: %@", formattedOutput);
 
//--------------------------------------------
// Change local and output as currency
//--------------------------------------------
NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"it_IT"];
[formatter setLocale:locale];
formattedOutput = [formatter stringFromNumber:[attributesDict objectForKey:NSFileSystemFreeSize]];
NSLog(@"Output as currency - locale it_IT: %@", formattedOutput);

The output is now shown in the current locale (US) as well as the it_IT locale:

NSNumberFormatter and Percentage

The example below shows the output for percentage style output. In this case, it shows the percentage of disk space available, using the system attributes dictionary defined above.

//--------------------------------------------
// Format style as percentage, output to console
//--------------------------------------------
[formatter setNumberStyle:NSNumberFormatterPercentStyle];
 
// Set to the current locale
[formatter setLocale:[NSLocale currentLocale]];
 
// Get percentage of system space that is available
float percent = [[attributesDict objectForKey:NSFileSystemFreeSize] floatValue] / [[attributesDict objectForKey:NSFileSystemSize] floatValue];
NSNumber *num = [NSNumber numberWithFloat:percent];
formattedOutput = [formatter stringFromNumber:num];
NSLog(@"Percentage of system space available: %@", formattedOutput);

NSNumberFormatter and Spell-Out Numbers

The final example shows how to use the spell-out style.

//--------------------------------------------
// Format style as "spell-out" output to console
//--------------------------------------------
[formatter setNumberStyle:NSNumberFormatterSpellOutStyle];
formattedOutput = [formatter stringFromNumber:[attributesDict objectForKey:NSFileSystemFreeSize]];
 
NSLog(@"Spell out: %@", formattedOutput);
 
// Clean up
[formatter release];
[locale release];

Share Your NSNumberFormatter Examples

I’m sure there are any number of interesting ways to leverage this class. If you have a formatter style that you’ve found helpful, please post a comment with a working code example.

10 comments

As always excellent example, thank you :)

In the last code blog I think I see a code creep :)
#define debug(format, …) CFShow([NSString stringWithFormat:format, ## __VA_ARGS__]);

Cheers, Marin

by Marin Todorov on Jun 16, 2010. #

Thanks Marin, yes that was some debug code I prefer to use over NSLog…I’ve removed the code.

by John Muchow on Jun 16, 2010. #

Any way to convert seconds into hours:minutes:seconds easily?

by Lucas Longo on Jun 16, 2010. #

There may be a way to use the NSDate class, however it may come down to doing the math yourself – divide by 3600 to get the hours, divide remainder by 60 to get minutes, etc. Anyone know of a better way ?

by John Muchow on Jun 16, 2010. #

For fun, you can use NSNumberFormatter to make a calculator that provides output in the spell-out style.

Throw together a quick window in IB, add 10 buttons for numbers, add four buttons for +, -, x, and divide, and one button for equals. Write some quick methods in Xcode, hook up the buttons to the methods. Oh yeah, create two outputs in IB, one for the numbers and one (larger) for the spell-out. Then have your equal method set the number output and spell-out output.

Quick and fun.

Also, you can add your (male hetronormative assumption ahead) wife’s name in the output randomly, or when the result is her age, or something. Throw the icon on the desktop and wait for her to need some calcs (or drag her over and force her to do some calcs).

Great fun, then she can go back to her normal life.

by Patrick on Jul 2, 2010. #

Can you post an example where instead of putting £2,000,000 it displays £2m, or say £10.5m. It should work on smaller figures too: ie: 1k, 0.75k, 3.25k, etc.

Thanks

by AD on Jul 4, 2010. #

I want the number 123456789.1234567 formatted to only 9 integers.

But setting max integers truncates from right to left, so maxints set to 3 you get:

789.2134567

I want 123.1234567

Is there a way to do this with just the formatter?

by BFleming on Oct 4, 2010. #

Thanks for your code, its helps me more.
But i have an issue,i used your code in ‘textfieldshouldEndEditing’, first time its work normally but when we going back to the textfield , and coming out of it , then the value changes.

For example i entered value for first time is 123456789123456789
and got this output 123,456,789,123,456,789
and now when we re-enter and exit from the textfield with or without editing, i am getting the value is 123.

and other issue is, its formatting upto 18 characters only
If entered more than 18 we getting other answer i.e., 9,223,372,036,854,775,807.

Thanks in advance
Bhaskar

by Bhaskar on Nov 9, 2011. #

Thanks! That helped me a lot!

by Lucas Lockie on Apr 23, 2012. #

Thanks

by Prakash on Jul 31, 2012. #