I know that you can convert a float into a string using
NSString *myString = [NSString stringWithF开发者_运维问答ormat:@"%f", myFloat];
My question is what OTHER methods exist in Objective-C that can do that same?
thanks.
You could use NSNumber
NSString *myString = [[NSNumber numberWithFloat:myFloat] stringValue];
But there's no problem doing it the way you are, in fact the way you have in your question is better.
in a simple way
NSString *floatString = @(myFloat).stringValue;
You can create your own category method. Something like
@interface NSString (Utilities)
+ (NSString *)stringWithFloat:(CGFloat)float
@end
@implementation NSString (Utilities)
+ (NSString *)stringWithFloat:(CGFloat)float
{
NSString *string = [NSString stringWithFormat:@"%f", float];
return string;
}
@end
Edit
Changed this to a class method and also changed the type from float
to CGFloat
.
You can use it as:
NSString *myFloat = [NSString stringWithFloat:2.1f];
float someVal = 22.3422f;
NSNumber* value = [NSNumber numberWithFloat:someVal];
NSLog(@"%@",[value stringValue]);
精彩评论