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?
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.
%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"
%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.
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];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With