Use the class NSNumberFormatter
. It is more versatile than the printf()
format specifiers and considers user location settings, such as which characters to use for fractional values and thousands separations. Beware of the %g
specifier: in addition to the potential rounding off of the last decimal place, it uses scientific notation for numbers from one million.
See the code below, assuming the program is running on a device with local configuration pt_BR:
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 output 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 meaningful digits, so meaningful digits, such as zeros after the decimal point, are not considered. See also how the %g
specifier handles precision for the integer part and the decimal part, as well as its scientific notation behavior for values with more than six digits for the integer part.
Take a look at NSNumberFormatter
class documentation % to see other configuration options. For example, you can set how rounding should be done, or disable thousands separation.