2
votes

My objective is to create a customer calculator application for iPhone and am using Xcode to write my application. My problem that I cannot find a solution for is how to format a number without using scientific notation or a set number of decimals.

I tried...

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

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

%f formatting always prints 6 digits after the decimal place so if the user types in "5" it displays 5.000000.

%g formatting jumps to scientific notation after 6 digits so 1000000 becomes 1e+06 when displayed.

I want to be able to have the following numbers display without pointless decimals or scientific notation:

123,456,789;
1.23456789;
12345.6789;
-123,456,789;
-1.23456789;
-12345.6789;
4
I edited your question a bit to conform with the general SO style guidelines and add %s to your format strings. If I misrepresented something, please let me know! Also, good first question. - Carl Veazey
Well, if you want to avoid decimals I'd suggest octal notation. You could use binary, of course, but it's not very compact. - Hot Licks

4 Answers

2
votes

For floating point number formatting you can use %f, and you have to specify the minimum field width and the precision in terms of characters. If you use %4.2f, means four characters wide minimum (if less than 4 are used, will be filled with blank spaces at left) and 2 characters for precision. If you want 10 characters of minimum wide and 0 of decimal precision, you use %10.0f .

In your particular case, you should use %.0f for no digits of decimal precision.

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

You can find a quick reference here . Is not the objective-c documentation, but is equivalent.

For the sake of completeness, you can find the documentation of the specification that NSString formatting follows in:

https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Strings/Articles/FormatStrings.html

and here:

http://pubs.opengroup.org/onlinepubs/009695399/functions/printf.html

EDIT for truncation:

buttonScreen.text = [NSString stringWithFormat:@"%d",(int)currentNumber];

But, you should read a little about floating representation, precision and casting to be aware of possible undesired behavior.

2
votes

Take a look at NSNumberFormatter.

Configured correctly, it can add commas when appropriate. You'll also need to tell it how many significant digits to use.

0
votes

You aren't interacting with Xcode and Objective-c as much as you suspect here, the underlying implementation is printf. Check out this tutorial on how to use printf format specifiers.

0
votes

So what do you want it to look like? The stringWithFormat formatting is a superset of the old C sprintf. So have you tried using d and variations to meet your liking?