Variable interpolation inside printf-style formatting functions

后端 未结 2 606
滥情空心
滥情空心 2020-12-19 06:16

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

相关标签:
2条回答
  • 2020-12-19 06:57

    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];
    
    0 讨论(0)
  • 2020-12-19 07:00

    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".

    0 讨论(0)
提交回复
热议问题