我在上传视频时会向用户显示一个字符串,内容类似
20% uploaded
因此,当百分比数字是单位数字时,我希望十位空间可以用空白字符填充。
喜欢我们如何多次显示01,02,03作为解决方案的单位数字,我想显示空格而不是0。
答案 0 :(得分:3)
可修改左值的答案适合于获得%和数字之间的首选空格。你只需要检查值,并相应地找到“%”符号。 或者还有另一种方式。
e.g。我正在使用以下格式显示%符号。
[NSString stringWithFormat:@“%。0f %% of 100% 上传..“,progressValue * 10];
这相应地管理了您的值和'%'符号之间的空格。
答案 1 :(得分:2)
您需要将格式设置为%<alighmentInteger>d
您可以将值存储到stringWithFormat:
仅用于显示我是直接NSLogging。
NSLog(@"%3d%%",i); //this will pad 3 white spaces.
如果您想要2个空格,请使用2d
E.g:
for (int i=0; i<101; i+=25) {
NSLog(@"%3d%% uploaded",i);
}
输出:
2013-04-16 11:55:16.002 DynamicObject[48056:303] 0% uploaded 2013-04-16 11:55:16.003 DynamicObject[48056:303] 25% uploaded 2013-04-16 11:55:16.003 DynamicObject[48056:303] 50% uploaded 2013-04-16 11:55:16.004 DynamicObject[48056:303] 75% uploaded 2013-04-16 11:55:16.004 DynamicObject[48056:303] 100% uploaded
答案 2 :(得分:1)
我能想到的最好的想法是检查价值。如果小于10,则打印空白字符。您可以使用 %.*s
将其合并到printf:printf("%.*s%d%% uploaded", value < 10, " ", value);
编辑:根据规范,字段宽度*
(或十进制整数)会为您执行此操作:printf("%*d%% uploaded", 2, value);
(或{{1} })
答案 3 :(得分:1)
这是一个返回所需输出的方法
- (NSString *)uploadProgress:(NSUInteger)progress {
return [NSString stringWithFormat:@"%@%% uploaded", progress < 10 ?
[NSString stringWithFormat:@" %i", progress] :
[NSString stringWithFormat:@"%i", progress]];
}
呼叫:
NSLog(@"%@", [self uploadProgress:5]);
NSLog(@"%@", [self uploadProgress:50]);
输出:
2013-04-16 02:24:49.948 stackoverflow test001[11587:c07] 5% uploaded
2013-04-16 02:24:49.949 stackoverflow test001[11587:c07] 50% uploaded