38

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?

CodeGuy
  • 28,427
  • 76
  • 200
  • 317
  • check this post: http://stackoverflow.com/questions/739682/how-to-add-percent-sign-to-nsstring – Di Wu Jan 03 '11 at 15:55
  • The format specifiers can be found at http://developer.apple.com/documentation/Cocoa/Conceptual/Strings/Articles/formatSpecifiers.html – NiKKi Jul 27 '12 at 06:29

2 Answers2

86

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

float someFloat = 40.233f;
NSString *str = [NSString stringWithFormat:@"%.02f%%",someFloat];
F'x
  • 12,105
  • 7
  • 71
  • 123
13

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.

Community
  • 1
  • 1
spolu
  • 680
  • 5
  • 11