How can I convert an int to an NSString?

2020-01-24 19:56发布

I'd like to convert an int to a string in Objective-C. How can I do this?

标签: objective-c
4条回答
SAY GOODBYE
2楼-- · 2020-01-24 20:13

Primitives can be converted to objects with @() expression. So the shortest way is to transform int to NSNumber and pick up string representation with stringValue method:

NSString *strValue = [@(myInt) stringValue];

or

NSString *strValue = @(myInt).stringValue;
查看更多
够拽才男人
3楼-- · 2020-01-24 20:14
int i = 25;
NSString *myString = [NSString stringWithFormat:@"%d",i];

This is one of many ways.

查看更多
淡お忘
4楼-- · 2020-01-24 20:17
NSString *string = [NSString stringWithFormat:@"%d", theinteger];
查看更多
唯我独甜
5楼-- · 2020-01-24 20:21

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:

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.

查看更多
登录 后发表回答