Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable interpolation inside printf-style formatting functions

Is there a way to pass a variable for the floating point precision parameter in printf-style string formatting functions in Objective-C (or even C)? For example, in TCL and other scripting languages, I can do something like this:

set precision 2
puts [format "%${precision}f" 3.14159]

and the output will be, of course, 3.14. I would like to do something similar in Objective-C:

float precision = 2
NSString *myString = [NSString stringWithFormat:@".2f", 3.14159]

except that I would like to include precision as a variable. How can this be done?

like image 313
Ampers4nd Avatar asked Jan 06 '12 17:01

Ampers4nd


People also ask

What will happen if you use wrong formatting characters in printf?

It is Undefined behavior! Undefined behavior means that anything can happen. It may show you results which you expect or it may not or it may crash.

What does %3f mean in C?

%3d can be broken down as follows: % means "Print a variable here" 3 means "use at least 3 spaces to display, padding as needed" d means "The variable will be an integer"

Which of the following is format specification for printing string in printf ()?

%s is the format specifier used to print a String or Character array in C Printf or Scanf function. This format specifier is used for characters.


1 Answers

Yes, the string format specifiers for printf, which are used by Cocoa for formatting, include a variable-precision specifier, * placed after the decimal point:

int precision = 3;
NSLog(@"%.*f", precision, 3.14159);
NSString *myString = [NSString stringWithFormat:@".*f", precision, 3.14159];
like image 124
jscs Avatar answered Oct 20 '22 01:10

jscs