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
CodeGuy
29k77 gold badges205 silver badges325 bronze badges
-
check this post: stackoverflow.com/questions/739682/…Di Wu– Di Wu2011年01月03日 15:55:01 +00:00Commented Jan 3, 2011 at 15:55
-
The format specifiers can be found at developer.apple.com/documentation/Cocoa/Conceptual/Strings/…NiKKi– NiKKi2012年07月27日 06:29:35 +00:00Commented Jul 27, 2012 at 6:29
2 Answers 2
% 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
F'x
12.4k8 gold badges75 silver badges125 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
Van Du Tran
what about type double?
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.
Comments
Explore related questions
See similar questions with these tags.
default