objective-c – NSNumberFormatter领先0和小数

前端之家收集整理的这篇文章主要介绍了objective-c – NSNumberFormatter领先0和小数前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
有没有办法格式化前导0和小数的NSNumber?例如,我需要有能力写入4.5和000.目前我有它允许小数,但不是0的前导.
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’作为输出.

我看过Apple的“数据格式指南”但没有取得多大成功.

解决方法

请注意,[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

如果你没有字符串,只需创建数字,如:

myNumber = [NSNumber numberWithFloat:4.5];
myNumber = [NSNumber numberWithInt:0];

或者只使用标准格式:

myString = [NSString stringWithFormat:@"%.1f",[myNumber floatValue]];
myString = [NSString stringWithFormat:@"%03d",[myNumber intValue]];

或者,如果您不需要NSNumber表示,只需使用标准格式:

myString = [NSString stringWithFormat:@"%.1f",4.5];
myString = [NSString stringWithFormat:@"%03d",0];

猜你在找的C&C++相关文章