Variable interpolation inside printf-style formatting functions

后端 未结 2 623
滥情空心
滥情空心 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 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".

提交回复
热议问题