Search code examples
objective-cnsnumbernsnumberformatter

NSNumberFormatter Scientific Form Output


I have NSNumber and NSResultFormatter, that converts number into string and displays it on screen.

In scientific form output for large numbers is "1.345e10" and for small numbers is "1.345e-10".

I want to output large numbers as "1.345e+10", like in standart iOS calc app. How can I to do it?


Solution

  • You can achieve that by setting a custom number format, for example:

    NSNumberFormatter *fmt = [[NSNumberFormatter alloc] init];
    [fmt setExponentSymbol:@"e"];
    [fmt setPositiveFormat:@"0.###E+0"];
    NSString *s = [fmt stringFromNumber:@(12345678900)];
    // 1.235e+10
    

    Custom number formats are documented in http://www.unicode.org/reports/tr35/tr35-25.html#Number_Format_Patterns.