How to get the numbers of numbers with decimal places (Xcode)
My goal is to create an iPhone calculator app for iPhone and I am using Xcode to write my app. My problem, which I can't seem to find a solution, is how to format a number that uses decimals (with padded zeros) without going into scientific notation
I tried...
buttonScreen.text = [NSString stringWithFormat:@"%0.f",currentNumber];
%0.f
formatting is always rounded, so if the user enters "4.23" it displays "4"
%f
formats numbers with 6 decimal places (input in '5' is displayed as "5.000000"), but I don't want to show extra zeros at the end of the number.
%10.4f
is something else I saw in my reading to find a solution, but my problem is that I don't know how many decimal places will be in the answer and I may need zero decimal places or 10 decimal places depending on to the number.
The following are examples of numbers that I would like to display (no commas): an integer greater 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 response to my previous question "How to format numbers without scientific notation or decimal places", which I poorly formulated in the way I intended to write "unnecessary (extra zeros)", but, rereading my post, clearly testified my inability to convey this at any point in my question.
source to share
Use the NSNumberFormatter class .
First, define a formatter:
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
Then you can define various formatting properties:
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 to string like this:
NSString *formattedNumber = [formatter stringFromNumber:num];
Play with him. It's pretty straightforward, but it might take some work to get the look you like.
source to share
Actually, it makes 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];
source to share