Yogini
Yogini

Reputation: 1721

How to convert int to NSString?

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

How can I do this?

Upvotes: 108

Views: 159296

Answers (4)

Rob
Rob

Reputation: 437372

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.

Upvotes: 2

VisioN
VisioN

Reputation: 145368

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;

Upvotes: 160

h4xxr
h4xxr

Reputation: 11465

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

This is one of many ways.

Upvotes: 38

Silfverstrom
Silfverstrom

Reputation: 29322

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

Upvotes: 146

Related Questions