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;
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.
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:
But, you should read a little about floating representation, precision and casting to be aware of possible undesired behavior.