Objective-C number formatting with NSNumberFormatter

Posted by – December 11, 2008

Today I finished an article to a local magazine about mobile development, this article gives a small introduction on iPhone development with iPhone SDK, this article covers the development of a simple application that perform some meansure conversion. One of learned things was how to do number formatting with NSNumberFormatter like we have below:

1
2
3
4
5
6
7
8
NSNumber *result = [NSNumber numberWithFloat: 0.0];

NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setFormatterBehavior:NSNumberFormatterBehavior10_4];
[numberFormatter setDecimalSeparator:@","];
[numberFormatter setFormat:@"0.00000;0.00000;-0.00000"];
   
NSString resultText = [[[numberFormatter stringFromNumber:result];

In this example I’m setting the number format to show a float number with 5 decimal positions and using comma as decimal separator since this is the brazilian decimal separator. I could convert and format a NSNumber by just passing it as argument to stringFromNumber method of NSNumberFormatter instance. Not so different from Java, right?

Share

3 Comments on Objective-C number formatting with NSNumberFormatter

  1. Gezerk says:

    I am a newbie to iPhone development, but I think the \\\’setFormat\\\’ message is only intended for use with the NSNumberFormatterBehavior10_0.
    Apple docs: http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSNumberFormatter_Class/Reference/Reference.html#//apple_ref/doc/uid/20000202-CHDCEHHC

  2. rogerio says:

    Well the code above works well on iPhone Simulator that comes with iPhone SDK 2.0 and 2.2 versions.

  3. Anthony Stevens says:

    \’setFormat\’ does not work on the actual iPhone. \’setFormat\’ will only work in the simulator. Instead use \’setNumberStyle\’.

    E.g. [numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>