Search code examples
iosiphonexcodedecimalnumber-formatting

How to get format numbers with decimals (XCode)


My objective is to create a customer calculator application for iPhone and I am using Xcode to write my application. My problem, that I cannot find a solution for, is how to format a number that uses decimals (with extra zeros) without switching into scientific notation

I tried...

buttonScreen.text = [NSString stringWithFormat:@"%0.f",currentNumber];

%0.f formatting always rounds so if the user types in "4.23" it displays "4"

%f formats numbers with 6 decimals (typing in '5' displays as '5.000000'), but I don't want to show extra zeros on the end of the number.

%10.4f is something else that I have seen in my reading to find the solution, but my problem is that I don't know how many decimals will be in the answer, and I may want zero decimals or 10 decimals depending on the number.

The following are examples of numbers I'd like to display (without the commas): A whole number larger than 6 digits, a decimal number with more than 6 digits.

123,456,789;
0.123456789;
12345.6789;
-123,456,789;
-0.23456789;
-12345.6789;

*This is a spiritual repost to my earlier question "How to Format Numbers without scientific notation or decimals" which I poorly phrased as I intended to write 'unnecessary (extra zeros),' but upon rereading my post clearly witnessed my inability to convey that at any point in my question.


Solution

  • Use the NSNumberFormatter class.

    First define the formatter:

    NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
    

    Then you can define various properties of the formatter:

    formatter.numberStyle = NSNumberFormatterDecimalStyle;
    formatter.maximumIntigerDigits = 3;
    formatter.minimumFractionDigits = 3;
    formatter.maximumFractionDigits = 8;
    formatter.usesSignificantDigits = NO;
    formatter.usesGroupingSeparator = YES;
    formatter.groupingSeparator = @",";
    formatter.decimalSeparator = @".";
    ....
    

    You format the number into a string like this:

    NSString *formattedNumber = [formatter stringFromNumber:num];
    

    Play around with it. Its pretty simple, but may take some work to get the look you would like.