Question

I would like to make it so one of my UILabels only shows a maximum of 3 digits. So, if the associated value is 3.224789, I'd like to see 3.22. If the value is 12.563, I'd like to see 12.5 and if the value is 298.38912 then I'd like to see 298. I've been trying to use NSNumberFormatter to accomplish this, but when I set the maximum significant digits to 3 it always has 3 digits after the decimal place. Here's the code:

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

I always thought 'significant digits' meant all the digits, before and after the decimal point. Anyway, is there a way of accomplishing this using NSNumberFormatter?

Thanks!

Était-ce utile?

La solution

I believe that

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

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

Autres conseils

Perhaps you also have to set (not sure though):

[distanceFormatter setUsesSignificantDigits: YES];

But in your case it's probably much easier to just use the standard string formatting:

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

(note: this will round the last digit)

Heres a small function 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.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top