How to format and print floating numbers in iOS?

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

Setup NSNumberFormatterusing <a>=6and<f>=2 : (the platform is the iOS 5.1 SDK, Xcode 4.3.3 and 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 Result (with German):Test: 2,64

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

: , . [nf setMaximumFractionDigits:4] [nf setMaximumFractionDigits:0]. , , . , ., .

. printf - NSNumberFormatter?

+5
1

. localizedStringWithFormat:

objective-c

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

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

SWIFT 3

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

, . !

+11

All Articles