views:

72

answers:

3

How can I include a percent symbol (%) in my NSString?

[NSString stringWithFormat:@"Downloading (%1.0%)",  percentage]

The above code does not include the last percent in the string.

+3  A: 

Use %% to escape the percent sign.

Carl Norum
Thanks! However, %% didn't work but %%% did. Go figure.
TomH
@TomH, then you still have something wrong with your code - check out @Mads answer for more details.
Carl Norum
A: 
[NSString stringWithFormat:@"Downloading (%g%%)",  percentage];
falconcreek
+2  A: 

Carl is right about the escaping, but it alone won't work with the code you have given. You are missing a format specifier after the first percentage sign. Given percentage is a double, try:

[NSString stringWithFormat:@"Downloading (%.1f %%)",  percentage];

Note the %.1f, for formatting a double with one decimal. This gives 45.5 %. Use %.f for no decimals.

Also see http://developer.apple.com/library/mac/#documentation/cocoa/conceptual/strings/Articles/formatSpecifiers.html

Mads Mobæk
Thanks very much -- can't believe that I was leaving out the format specifier. Looking at the code for far too long yesterday.
TomH