0

I have got a float value which is supposed to have a certain number of decimal places. The number of decimal places is stored in a variable.

Here is the line of code:

self.numberTextField.text = [NSString stringWithFormat:@"%.%df",result, [[NSUserDefaults standardUserDefaults] boolForKey:@"decimalPlaces"]];

My problem is that I do not know how to combine the %f and %d specifiers in the right way. Any ideas?

Thank for your answer!

2 Answers 2

1

You can replace a field width or precision by an asterisk (*) and it will then pick up the value from the parameter list.

int width = 5;
int precision = 2;
double value = 3.1415926;
NSString* formattedNumber = [NSString stringWithFormat: @"%*.*f", width, precision, value];

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

Consider also using an NSNumberFormatter. It has the advantage of being Internationalisation aware.

Sign up to request clarification or add additional context in comments.

Comments

0

I think you will have to do this in 2 stages

first create the formatted string with the desired number of decimal points:

NSString *format = [NSSString stringWithFormat:@"%%.%if", numberOfPlaces];

%% is an escaped percentage so the only part that will be replaced in the format will be %i, i.e. numberOfPlaces = 2 will give format = @"%.2f"

Then you use that format string to create the end result

NSString *valueString = [NSString stringWithFormat:format, myLongFloat];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.