printf样式格式功能中的变量插值

问题描述:

在Objective-C(甚至C)中的printf样式字符串格式化函数中,是否可以传递浮点精度参数的变量?例如,在TCL和其他脚本语言中,我可以执行以下操作:

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]

,输出当然是3.14.我想在Objective-C中做类似的事情:

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]

除了我想将precision作为变量包括在内.该怎么办?

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

是的,字符串格式说明符printf的/a>包括一个精度可变的说明符,*放在小数点后:

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];