简体   繁体   English

objective-C - 将float转换为字符串的其他方法

[英]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? 我的问题是Objective-C中存在哪些其他方法可以做到这一点?

thanks. 谢谢。

You could use NSNumber 你可以使用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 . 将其更改为类方法,并将类型从float更改为CGFloat

You can use it as: 您可以将其用作:

NSString *myFloat = [NSString stringWithFloat:2.1f];
float someVal = 22.3422f;
NSNumber* value = [NSNumber numberWithFloat:someVal];
NSLog(@"%@",[value stringValue]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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