-->

How to add percent sign to NSString

2019-01-01 03:37发布

问题:

I want to have a percentage sign in my string after a digit. Something like this: 75%.

How can I have this done? I tried:

[NSString stringWithFormat:@\"%d\\%\", someDigit];

But it didn\'t work for me.

回答1:

The code for percent sign in NSString format is %%. This is also true for NSLog() and printf() formats.



回答2:

The escape code for a percent sign is \"%%\", so your code would look like this

[NSString stringWithFormat:@\"%d%%\", someDigit];

Also, all the other format specifiers can be found at Conceptual Strings Articles



回答3:

If that helps in some cases, it is possible to use the unicode character:

NSLog(@\"Test percentage \\uFF05\");


回答4:

The accepted answer doesn\'t work for UILocalNotification. For some reason, %%%% (4 percent signs) or the unicode character \'\\uFF05\' only work for this.

So to recap, when formatting your string you may use %%. However, if your string is part of a UILocalNotification, use %%%% or \\uFF05.



回答5:

seems if %% followed with a %@, the NSString will go to some strange codes try this and this worked for me

NSString *str = [NSString stringWithFormat:@\"%@%@%@\", @\"%%\", 
                 [textfield text], @\"%%\"]; 


回答6:

uese following code.

 NSString *searchText = @\"Bhupi\"
 NSString *formatedSearchText = [NSString stringWithFormat:@\"%%%@%%\",searchText];

will output: %Bhupi%



回答7:

iOS 9.2.1, Xcode 7.2.1, ARC enabled

You can always append the \'%\' by itself without any other format specifiers in the string you are appending, like so...

int test = 10;

NSString *stringTest = [NSString stringWithFormat:@\"%d\", test];
stringTest = [stringTest stringByAppendingString:@\"%\"];
NSLog(@\"%@\", stringTest);

For iOS7.0+

To expand the answer to other characters that might cause you conflict you may choose to use:

- (NSString *)stringByAddingPercentEncodingWithAllowedCharacters:(NSCharacterSet *)allowedCharacters

Written out step by step it looks like this:

int test = 10;

NSString *stringTest = [NSString stringWithFormat:@\"%d\", test];
stringTest = [[stringTest stringByAppendingString:@\"%\"] 
             stringByAddingPercentEncodingWithAllowedCharacters:
             [NSCharacterSet alphanumericCharacterSet]];
stringTest = [stringTest stringByRemovingPercentEncoding];

NSLog(@\"percent value of test: %@\", stringTest);

Or short hand:

NSLog(@\"percent value of test: %@\", [[[[NSString stringWithFormat:@\"%d\", test] 
stringByAppendingString:@\"%\"] stringByAddingPercentEncodingWithAllowedCharacters:
[NSCharacterSet alphanumericCharacterSet]] stringByRemovingPercentEncoding]);

Thanks to all the original contributors. Hope this helps. Cheers!