How To Output % Character In NSString, NSLog Or Printf

Ever tried to output a % character in NSString, NSLog or printf statement?

NSLog(@"Percent complete: %d%", x);
printf("Percent complete: %d%\n", x + 10);
NSLog(@"Percent complete: %@%", [NSString stringWithFormat:@"%d\%", x + 20]);

The output looks as follows:

Percent complete: 10
Percent complete: 20
Percent complete: 30

Using the ‘typical’ escape sequence is of no help:

NSLog(@”Percent complete: %d\%”, x);
printf(“Percent complete: %d\\%\n”, x + 10);
NSLog(@”Percent complete: %@%\\\%”, [NSString stringWithFormat:@”%d\%”, x + 20]);

Percent complete:10
Percent complete: 20\
Percent complete: 30\

The answer is to use two % characters:

NSLog(@"Percent complete: %d%%", x);
printf("Percent complete: %d%%\n", x + 10);
NSLog(@"Percent complete: %@%%", [NSString stringWithFormat:@"%d", x + 20]);

Percent complete: 10%
Percent complete: 20%
Percent complete: 30%