NSNumberFormatter to show a maximum of 3 digits
Asked Answered
S

3

6

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!

Sg answered 23/3, 2012 at 16:3 Comment(0)
J
10

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.

Jeane answered 17/12, 2012 at 22:32 Comment(2)
Yes, this works great. Setting the usesSignificantDigits flag to YES is the key to this solution for the OP. I just used this, and indeed it works across the decimal point, for example it converts $19.17 to $19.20.Shantelleshantha
please check my question #35112706. It doesn't work for me in SwiftHalfbaked
W
4

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)

Willingham answered 23/3, 2012 at 16:41 Comment(0)
D
2

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.

Devilish answered 23/3, 2012 at 16:40 Comment(1)
Thanks for understanding the question. There is a difference between "significant digits" and "number of digits to the right of the decimal point."Janiuszck

© 2022 - 2024 — McMap. All rights reserved.