简体   繁体   中英

objective-C - other methods to convert a float to string

I know that you can convert a float into a string using

NSString *myString = [NSString stringWithFormat:@"%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.

以一种简单的方式

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]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM