How do I set the fill character for displaying numbers (Objective C)
-
12-09-2019 - |
Question
I'm trying to format a string to give me 2 characters for a number, no matter what its value. Right now, I have
[NSString stringWithFormat:@"%2d:%2d:%2d",h,m,s)];
and for the values 1, 2, 3, the output is
1: 2: 3
How do I change the spaces to 0's ?
Solution
This is done the same as C's printf (see man 3 printf):
[NSString stringWithFormat:@"%02d:%02d:%02d",h,m,s];
(By the way, if you're trying to format dates or times, I'd suggest looking at NSDateFormatter.)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow