NSString stringWithFormat adding a percent [duplicate]

爷,独闯天下 提交于 2019-11-27 17:06:37

问题


This question already has an answer here:

  • How to add percent sign to NSString 7 answers

How can I add a percent to my stringWithFormat function? For example, I'd like to have the following:

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?


回答1:


% being the character beginning printf-style formats, it simply needs to be doubled:

float someFloat = 40.233f;
NSString *str = [NSString stringWithFormat:@"%.02f%%",someFloat];



回答2:


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.

Cited from How to add percent sign to NSString.



来源:https://stackoverflow.com/questions/4585904/nsstring-stringwithformat-adding-a-percent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!