[英]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. 谢谢。
以一种简单的方式
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.