NSNumberformatter加零 [英] NSNumberformatter add extra zero

查看:73
本文介绍了NSNumberformatter加零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种将"1"显示为"01"的方法,因此基本上所有低于10的内容都应以0开头.

I'm looking for a way to display "1" as "01", so basically everything below 10 should have a leading 0.

什么是最好的方法? 我知道我可以使用简单的if结构来执行此检查,但是使用NSNumberformatter应该可以做到这一点吧?

What would be the best way to do this? I know I can just use a simple if structure to do this check, but this should be possible with NSNumberformatter right?

推荐答案

如果您只想使用NSString,则只需执行以下操作:

If you just want an NSString, you can simply do this:

NSString *myNumber = [NSString stringWithFormat:@"%02d", number];

%02d来自C.%nd表示字符串中至少应包含n个字符,如果少于,请用0填充.这是一个示例:

The %02d is from C. %nd means there must be at least n characters in the string and if there are less, pad it with 0's. Here's an example:

NSString *example = [NSString stringWithFormat:@"%010d", number];

如果number变量只有两位数字,那么它将以八个零作为前缀.如果它是9位数字,则将以单个零作为前缀.

If the number variable only was two digits long, it would be prefixed by eight zeroes. If it was 9 digits long, it would be prefixed by a single zero.

如果要使用NSNumberFormatter,可以执行以下操作:

If you want to use NSNumberFormatter, you could do this:

NSNumberFormatter * numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setPaddingPosition:NSNumberFormatterPadBeforePrefix];
[numberFormatter setPaddingCharacter:@"0"];
[numberFormatter setMinimumIntegerDigits:10];
NSNumber *number = [NSNumber numberWithInt:numberVariableHere];

----更新------ 我认为这可以解决您的问题:

----UPDATE------ I think this solves your problem:

[_minutes addObject:[NSNumber numberWithInt:i]];
return [NSString stringWithFormat:@"%02d", [[_minutes objectAtIndex:row] intValue]]; 

这篇关于NSNumberformatter加零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆