有没有办法格式化前导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];