How to format and print float numbers on iOS?

user8472 picture user8472 · Jul 19, 2012 · Viewed 9.9k times · Source

I would like to create a formatted output of a floating point number with correct localization on Cocoa-Touch. The output should be equivalent to that of printf("%<a>.<b>f", n), where <a> is the total number of digits and <f> is the maximum number of fractional digits.

Setup of NSNumberFormatter with <a>=6 and <f>=2: (Platform is iOS 5.1 SDK, Xcode 4.3.3 and the iPhone Simulator 5.1)

NSNumberFormatter *nf = [[NSNumberFormatter alloc] init];
[nf setNumberStyle:NSNumberFormatterDecimalStyle];
[nf setPaddingCharacter:@" "];
[nf setUsesGroupingSeparator:NO];
[nf setLocale:[NSLocale autoupdatingCurrentLocale]];
[nf setUsesSignificantDigits:YES];
[nf setMaximumSignificantDigits:6];
[nf setMaximumFractionDigits:2];
[nf setRoundingMode:NSNumberFormatterRoundFloor];
NSLog(@"Test: %@", [nf stringFromNumber:[NSNumber numberWithDouble:2.64324897]]);

Expected output (with German locale): Test: 2,64

Observed output (with German locale): Test: 2,64324

Other observations: I have tried to use different values for the fraction digits, e.g. [nf setMaximumFractionDigits:4] or [nf setMaximumFractionDigits:0]. The result is unchanged, it appears that the fraction digits are ignored. Changing the locale to US only changes the , to a ., not the number of fraction digits.

Question: How can I translate the printf-format string correctly to an NSNumberFormatter?

Answer

JFS picture JFS · Jun 13, 2013

Ryan is not totally wrong. Use the localizedStringWithFormat method:

using objective-c

NSNumber *yourNumber = [nf numberFromString:yourString];
//to create the formatted NSNumber object

NSString *yourString = [NSString localizedStringWithFormat:@"%.2F", yourNumber];
//to create the localized output

using SWIFT 3

let yourString: String
yourString = String.localizedStringWithFormat("%.2F", yourDoubleNumber) //no need for NSNumber Object

A little bit late but it still might help. Good luck!