objective-c 如何将 int 转换为 NSString?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1372715/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I convert an int to an NSString?
提问by Yogini
I'd like to convert an int to a string in Objective-C. How can I do this?
我想在 Objective-C 中将 int 转换为字符串。我怎样才能做到这一点?
回答by VisioN
Primitives can be converted to objects with @()expression. So the shortestway is to transform intto NSNumberand pick up string representation with stringValuemethod:
原语可以转换为带有@()表达式的对象。所以,最短的途径是转变int来NSNumber,拿起用字符串表示stringValue方法:
NSString *strValue = [@(myInt) stringValue];
or
或者
NSString *strValue = @(myInt).stringValue;
回答by Silfverstrom
NSString *string = [NSString stringWithFormat:@"%d", theinteger];
回答by h4xxr
int i = 25;
NSString *myString = [NSString stringWithFormat:@"%d",i];
This is one of many ways.
这是许多方法之一。
回答by Rob
If this string is for presentation to the end user, you should use NSNumberFormatter. This will add thousands separators, and will honor the localization settings for the user:
如果此字符串用于呈现给最终用户,则应使用NSNumberFormatter. 这将添加数千个分隔符,并将遵守用户的本地化设置:
NSInteger n = 10000;
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
formatter.numberStyle = NSNumberFormatterDecimalStyle;
NSString *string = [formatter stringFromNumber:@(n)];
In the US, for example, that would create a string 10,000, but in Germany, that would be 10.000.
例如,在美国,这将创建一个 string 10,000,但在德国,这将是10.000.

