NSNumberFormatter领先0和小数 [英] NSNumberFormatter leading 0's and decimals
问题描述
有没有办法用前导0和小数格式化NSNumber?例如,我需要能够写入4.5和000.目前我有它允许小数,但不是0的前导。
Is there any way to format an NSNumber with leading 0's and decimals? For example, I need to have the ability to write 4.5 as well as 000. Currently I have it where it will allow decimals, but not leading 0's.
NSNumberFormatter *f = [[NSNumberFormatter alloc] init];
f.numberStyle = NSNumberFormatterNoStyle;
NSString *myString = [f numberFromString:@"4.5"];
NSLog(@"myString: %@",myString);
NSString *myOtherString = [f numberFromString:@"000"];
NSLog(@"myOtherString:%@",myOtherString);
上面的输出是:'myString:4.5'和'myOtherString:0'。我需要能够同时输出'4.5'和'000'作为输出。
The output from above would be: 'myString:4.5' and 'myOtherString:0'. I need to be able to do both '4.5' and '000' as output.
我看过Apple的数据格式指南并没有取得多大成功。
I have looked at Apple's "Data Formatting Guide" without much success.
推荐答案
请注意 [f numberFromString:@4.5]
返回 NSNumber *
不是 NSString *
你想要这样的东西:
NSNumberFormatter *f = [[NSNumberFormatter alloc] init];
f.numberStyle = NSNumberFormatterNoStyle;
NSNumber *myNumber;
NSString *myString;
myNumber = [f numberFromString:@"4.5"];
[f setNumberStyle:kCFNumberFormatterDecimalStyle];
myString = [f stringFromNumber:myNumber];
NSLog(@"myString: %@",myString);
myNumber = [f numberFromString:@"000"]; // Note that the extra zeros are useless
[f setFormatWidth:3];
[f setPaddingCharacter:@"0"];
myString = [f stringFromNumber:myNumber];
NSLog(@"myString: %@",myString);
NSLog输出:
myString:4.5
myString:000
myString: 4.5
myString: 000
如果你没有字符串开头只需创建数字:
If you don't have strings to start with just create number like:
myNumber = [NSNumber numberWithFloat:4.5];
myNumber = [NSNumber numberWithInt:0];
或者只是使用标准格式:
Or just use standard formatting:
myString = [NSString stringWithFormat:@"%.1f", [myNumber floatValue]];
myString = [NSString stringWithFormat:@"%03d", [myNumber intValue]];
或者如果你不需要 NSNumber
表示只使用标准格式:
Or if you don't need an NSNumber
representation just use standard formatting :
myString = [NSString stringWithFormat:@"%.1f", 4.5];
myString = [NSString stringWithFormat:@"%03d", 0];
这篇关于NSNumberFormatter领先0和小数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!