NSNumberformatter add extra zero

蹲街弑〆低调 提交于 2019-12-18 02:51:01

问题


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

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?


回答1:


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

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

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];

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.

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]]; 



回答2:


FIXED for Swift 3

let x = 999.1243
let formatter = NumberFormatter()
formatter.minimumFractionDigits = 1 // for float
formatter.maximumFractionDigits = 1 // for float
formatter.minimumIntegerDigits = 10 // digits do want before decimal
formatter.paddingPosition = .beforePrefix
formatter.paddingCharacter = "0"

let s = formatter.string(from: NSNumber(floatLiteral: x))!

OUTPUT

"0000000999.1"



来源:https://stackoverflow.com/questions/11131457/nsnumberformatter-add-extra-zero

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!