Format number in Objective-C

Asked

Viewed 395 times

3

I have an app that makes a calculation and returns a float, guy 4/2 = 2.00 but I would like this calculation to show only the 2, and if the result were decimal places with different numbers of 0 it showed the decimals.

How to show a result float ignoring the unnecessary zeroes?

  • Remembering that when compiling supporting 64 bit environments you should not use the float directly. Instead always use CGFloat. It will set the correct scalar based on the environment you are running.

2 answers

6

Using %g to define accuracy, do something like this:

float num1 = 2.00;
float num2 = 2.34;

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

Exit:

2, 2.34

3

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.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.