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];总结
以上是内存溢出为你收集整理的objective-c – NSNumberFormatter领先0和小数全部内容,希望文章能够帮你解决objective-c – NSNumberFormatter领先0和小数所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)