NSString stringWithFormat adding a percent

39,693

Solution 1

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

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

Solution 2

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.

Share:
39,693
CodeGuy
Author by

CodeGuy

Updated on April 17, 2020

Comments

  • CodeGuy
    CodeGuy about 4 years

    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?