开发者

NSString stringWithFormat adding a percent [duplicate]

开发者 https://www.devze.com 2023-02-02 09:58 出处:网络
This question already has answers here: How to add percent sign to NSString 开发者_运维知识库 (7 answers)
This question already has answers here: How to add percent sign to NSString 开发者_运维知识库 (7 answers) Closed 8 years ago.

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?


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

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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消