ohho
ohho

Reputation: 51941

How to use NSNumberFormatter to format numbers to a NSString of limited characters?

For example, a calculator can only display a maximum of 9 characters.

          1/2  ->        0.5
          2/3  ->  0.6666667
          3/4  ->       0.75
      20000/3  ->  6666.6667
123456x123456  ->  1.5241E10
                   ---------
                   123456789

Upvotes: 0

Views: 715

Answers (1)

Rich
Rich

Reputation: 8202

Set the setMaximumSignificantDigits: on the NSNumberFormatter.

 [numberFormatter setUsesSignificantDigits:YES];
 [numberFormatter setMaximumSignificantDigits:9];
 [numberFormatter setNumberStyle:NSNumberFormatterScientificStyle];

For whole number integers with more than 9 digits, there's not much you can do except use the NSNumberFormatterScientificStyle.

After checking this with a small program (see below) - you're still going to have issues with multi digit exponents. You might be better off having multiple NSNumberFormatters and check what the number is before displaying it. I'll have a quick play around and update this when I have a more robust solution.

(Directly from CodeRunner copy and paste)

#import <Foundation/Foundation.h>

static void test(NSNumber *n)
{
    NSNumberFormatter *f = [NSNumberFormatter new];
    [f setUsesSignificantDigits:YES];
    [f setMaximumSignificantDigits:9];
    [f setNumberStyle:NSNumberFormatterScientificStyle];
    NSString *s = [f stringFromNumber:n];
    NSLog(@"%@ -> %@ (%lu)", n, s, [s length]);
}

int main(int argc, char *argv[]) {
    @autoreleasepool {
        test(@(1.0/2));
        test(@(2.0/3));
        test(@(3.0/4));
        test(@(20000.0/2));
        test(@(123456*123456));
        test(@(0.000000000001));
        test(@(123456789.000000000001));
        test(@(12345.9999999999999));
    }
}

Output

2014-04-24 12:33:01.480 Untitled[3006:507] 0.5 -> 5E-1 (4)
2014-04-24 12:33:01.481 Untitled[3006:507] 0.6666666666666666 -> 6.66666667E-1 (13)
2014-04-24 12:33:01.481 Untitled[3006:507] 0.75 -> 7.5E-1 (6)
2014-04-24 12:33:01.482 Untitled[3006:507] 10000 -> 1E4 (3)
2014-04-24 12:33:01.482 Untitled[3006:507] -1938485248 -> -1.93848525E9 (13)
2014-04-24 12:33:01.483 Untitled[3006:507] 1e-12 -> 1E-12 (5)
2014-04-24 12:33:01.483 Untitled[3006:507] 123456789 -> 1.23456789E8 (12)
2014-04-24 12:33:01.484 Untitled[3006:507] 12346 -> 1.2346E4 (8)

Upvotes: 1

Related Questions