Search code examples
ioscocoansnumberformatter

Formatting a string with NSNumberFormatter


I have this app of mine where one text field must behave like a calculator display would. The number this text field shows is calculated by a function. If the number is, for example, "3.21" it should be displayed like this, with 2 decimal places. If the number has more decimal places, it should be displayed with the number of decimal places it has.

The textfield allows displaying 10 digits.

If the number is bigger than 9999999999 (10 nines) it should be displayed in scientific notation, like "4.767 E20" or something like that.

I suppose I have to use NSNumberFormatter for that matter but I see that I will have a series of ifs and a complicate sequence of NSNumberFormatters to do the job, specially for the number of decimal places.

My question is: is this the way to go or is there some kind of NSNumberFormatter that can do this automatically?


Solution

  • You don't need to use a number formatter at all. You can use the %g format string, from either Swift or Objective-C. The Swift code would look like this:

    import UIKit
    var value = 0.0
    for digits in 1...12 {
      value = value * 10 + 9
      print(String(format:"%.10g", value))
    }
    

    That yields the result:

    9
    99
    999
    9999
    99999
    999999
    9999999
    99999999
    999999999
    9999999999
    1e+11
    1e+12
    

    In Objective-C, you'd use NSString's stringWithFormat method, and also use the format string @"%.10g"

    My Objective-C is getting rusty, but the code would look something like this:

    double value = 0;
    for (int x = 0; x < 12; x++) {
      value = value * 10 + 9;
      NSString *result = [NSString stringWithFormat: @"%.10g", value];
      NSLog(@"value = %@", result);
    }