ios NSString stringWithFormat 添加一个百分比
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4585904/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
NSString stringWithFormat adding a percent
提问by CodeGuy
How can I add a percent to my stringWithFormat function? For example, I'd like to have the following:
如何在 stringWithFormat 函数中添加百分比?例如,我想要以下内容:
float someFloat = 40.233f;
NSString *str = [NSString stringWithFormat:@"%.02f%",someFloat];
This should cause the string to be:
这应该导致字符串为:
40.23%
But it is not the case. How can I achieve this?
但事实并非如此。我怎样才能做到这一点?
回答by F'x
%
being the character beginning printf-style formats, it simply needs to be doubled:
%
作为以 printf 样式格式开头的字符,它只需要加倍:
float someFloat = 40.233f;
NSString *str = [NSString stringWithFormat:@"%.02f%%",someFloat];
回答by spolu
The escape code for a percent sign is “%%”, so your code would look like this
百分号的转义码是“%%”,所以你的代码看起来像这样
[NSString stringWithFormat:@"%d%%", someDigit];
This is also true for NSLog() and printf() formats.
对于 NSLog() 和 printf() 格式也是如此。
Cited from How to add percent sign to NSString.