Objective-C number formatting with NSNumberFormatter
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?
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
January 21st, 2009 | #
Well the code above works well on iPhone Simulator that comes with iPhone SDK 2.0 and 2.2 versions.
January 21st, 2009 | #
\’setFormat\’ does not work on the actual iPhone. \’setFormat\’ will only work in the simulator. Instead use \’setNumberStyle\’.
E.g. [numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
May 12th, 2009 | #