How to convert int to NSString?

Objective C

Objective C Problem Overview


I'd like to convert an int to a NSString in Objective C.

How can I do this?

Objective C Solutions


Solution 1 - Objective C

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;

Solution 2 - Objective C

NSString *string = [NSString stringWithFormat:@"%d", theinteger];

Solution 3 - Objective C

int i = 25;
NSString *myString = [NSString stringWithFormat:@"%d",i];

This is one of many ways.

Solution 4 - Objective C

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionYoginiView Question on Stackoverflow
Solution 1 - Objective CVisioNView Answer on Stackoverflow
Solution 2 - Objective CSilfverstromView Answer on Stackoverflow
Solution 3 - Objective Ch4xxrView Answer on Stackoverflow
Solution 4 - Objective CRobView Answer on Stackoverflow