Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format and print float numbers on iOS?

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?

like image 728
user8472 Avatar asked Jul 19 '12 10:07

user8472


1 Answers

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!

like image 144
JFS Avatar answered Sep 28 '22 21:09

JFS