NSNumberFormatter to show a maximum of 3 digits

I would like to make one of my UILabels show a maximum of 3 digits. So, if the associated value is 3.224789, I would like to see 3.22. If the value is 12.563, I would like to see 12.5, and if the value is 298.38912, then I would like to see 298. I tried to use NSNumberFormatter for this, but when I set the maximum significant digits to 3 it always has 3 digits after the decimal place. Here is the code:

NSNumberFormatter *distanceFormatter = [[[NSNumberFormatter alloc] init] autorelease]; [distanceFormatter setNumberStyle:NSNumberFormatterDecimalStyle]; [distanceFormatter setAlwaysShowsDecimalSeparator:NO]; [distanceFormatter setMaximumSignificantDigits:3]; 

I always thought that “significant digits” means all digits before and after the decimal point. Anyway, is there a way to accomplish this using NSNumberFormatter?

Thanks!

+6
source share
3 answers

I think that

 NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init]; formatter.usesSignificantDigits = YES; formatter.maximumSignificantDigits = 3; 

will do exactly what you want, i.e. exactly 3 digits will always be displayed, be it 2 to decimal and 1 after or 1 to decimal and 2 after.

+10
source

You might also need to install (not sure):

[distanceFormatter setUsesSignificantDigits: YES];

But in your case, it might be much easier to just use standard string formatting:

 CGFloat yourNumber = ...; NSString* stringValue = [NSString stringWithFormat: @"%.3f", yourNumber]; 

(note: this will round the last digit)

+4
source

Here is a small function that I wrote:

 int nDigits(double n) { n = fabs(n); int nDigits = 0; while (n > 1) { n /= 10; nDigits++; } return nDigits; } NSString *formatNumber(NSNumber *number, int sigFigures) { double num = [number doubleValue]; int numDigits = nDigits(num); NSString *format = [NSString stringWithFormat:@"%%%i.%ilf", sigFigures -= numDigits, sigFigures]; return [NSString stringWithFormat:format, num]; } 

In my tests, this worked fine.

+2
source

Source: https://habr.com/ru/post/911515/


All Articles