Billy Fleming
Billy Fleming

Reputation: 65

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.

Upvotes: 3

Views: 16299

Answers (3)

Mike Gledhill
Mike Gledhill

Reputation: 29161

Actually, it makes more sense to use this:

label.text = [NSString stringWithFormat:@"%.4f", answer];

This tells XCode to display your number with 4 decimal places, but it doesn't try to "pad" the front of the number with spaces. For example:

1.23 ->  "    1.2300"   //  When using [NSString stringWithFormat:@"%9.4f", answer];
1.23 ->  "1.2300"       //  When using [NSString stringWithFormat:@"%.4f", answer];

Upvotes: 3

Jbryson
Jbryson

Reputation: 2905

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.

Upvotes: 10

Rachel Gallen
Rachel Gallen

Reputation: 28563

try something like this

label.text = [NSString stringWithFormat:@"%9.4f", answer];

where the 9 means total digits (in terms of padding for alignment), and the 4 means 4 decimal places.

Upvotes: 1

Related Questions