Format number in Objective-C

3

I have an app that does a calculation and returns a float , type 4/2 = 2.00 but would like this calculation to show only the 2 , and if the result was with decimal places with numbers other than 0 it would show the decimals.

How to show a% cos result that ignores unnecessary zeros?

    
asked by anonymous 12.03.2014 / 11:22

2 answers

6

Using % g to set the precision, do something like this:

float num1 = 2.00;
float num2 = 2.34;

NSLog(@"%g, %g", num1, num2);

Output:

  

2, 2.34

    
12.03.2014 / 12:14
3

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.

    
20.04.2014 / 10:35