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
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];
You can do it by making your format string a variable, and then passing that to stringWithFormat, like this:
float precision = 2;
NSString* formatString = [NSString stringWithFormat:@"%%.%df", precision];
NSString* myString = [NSString stringWithFormat:formatString, 3.14159];
The format string says you want a "%" symbol followed by a "." and then the value stored in the variable "precision" followed by "f".