printf样式格式功能中的变量插值 [英] Variable interpolation inside printf-style formatting functions

查看:74
本文介绍了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];

这篇关于printf样式格式功能中的变量插值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆