Use the class NSNumberFormatter
. It is more versatile than the format specifiers of printf()
and considers user location settings, such as which characters to use for fractional values and thousands separation. Beware of the specifier %g
: in addition to the potential rounding of the last decimal place, it uses scientific notation for numbers starting from one million.
See the code below, considering that the program is running on a device with pt_BR location configuration:
NSNumberFormatter *nf = [NSNumberFormatter new];
nf.numberStyle = kCFNumberFormatterDecimalStyle;
nf.usesSignificantDigits = YES;
nf.maximumSignificantDigits = 15;
NSLog(@"%%g = %g", 2.0);
NSLog(@"NSNumberFormatter = %@", [nf stringFromNumber:@2.0]);
NSLog(@"-----");
NSLog(@"%%g = %g", 2.123456789);
NSLog(@"%%.15g = %.15g", 2.123456789);
NSLog(@"NSNumberFormatter = %@", [nf stringFromNumber:@2.123456789]);
NSLog(@"-----");
NSLog(@"%%g = %g", 1000.0 * 1000.0);
NSLog(@"%%15g = %15g", 1000.0 * 1000.0);
NSLog(@"NSNumberFormatter = %@", [nf stringFromNumber:@(1000.0 * 1000.0)]);
The exit is:
%g = 2
NSNumberFormatter = 2
-----
%g = 2.12346
%.15g = 2.123456789
NSNumberFormatter = 2,123456789
-----
%g = 1e+06
%15g = 1e+06
NSNumberFormatter = 1.000.000
The formatter has been configured to consider significant digits, so digits nay significant, such as zeros after the decimal point, are not considered. See also the specifier %g
accurately handles the entire part and decimal part as well as its scientific notation behavior for values with more than six digits for the entire part.
Take a look at class documentation NSNumberFormatter
to see other configuration options. For example, you can configure how to round or disable thousands separation.
Remembering that when compiling supporting 64 bit environments you should not use the
float
directly. Instead always useCGFloat
. It will set the correct scalar based on the environment you are running.– Douglas Fischer