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?

asked Jan 3, 2011 at 15:51
2

2 Answers 2

86

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

float someFloat = 40.233f;
NSString *str = [NSString stringWithFormat:@"%.02f%%",someFloat];
answered Jan 3, 2011 at 15:54
Sign up to request clarification or add additional context in comments.

1 Comment

what about type double?
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.

answered Jan 3, 2011 at 15:56

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.