How to convert int to NSString? - objective-c

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

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;

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

int i = 25;
NSString *myString = [NSString stringWithFormat:#"%d",i];
This is one of many ways.

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.

Related

Objective-C: Double to NSString with x-many decimals

I know that I can cast a double to a NSString with a specific amount of decimals like so:
double myDouble = 123.456789;
NSString *myString = [NSString stringWithFormat:#"%.4g", myDouble];
But how can I replace the number "4" in this example with a int variable?
Something like this doesn't work:
double myDouble = 123.456789;
int precision = 4;
NSString *myString = [NSString stringWithFormat:#"%.%dg", myDouble, precision];
Consider using NSNumberFormatter:
double myDouble = 123.456789;
int precision = 4;
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
formatter.minimumFractionDigits = precision;
formatter.maximumFractionDigits = precision;
NSString *myString = [formatter stringFromNumber:#(myDouble)];
Or, if you want this in scientific notation, you can alternatively specify something like:
formatter.numberStyle = NSNumberFormatterScientificStyle;
formatter.usesSignificantDigits = YES;
formatter.minimumSignificantDigits = precision;
formatter.maximumSignificantDigits = precision;
It just depends upon what precisely you're looking for.
This also has the virtue of also honoring the user's regional settings (e.g. if in Germany, the decimal separator is a comma, not a period).
If you need to force the locale setting (e.g. this is for creating something that will be exchanged with a web service that expects the data in a specified format), you can set the formatter's locale (e.g. [NSLocale localeWithLocaleIdentifier:#"en_US"]). But when presenting results in the user interface, you always want to honor the device's locale settings.
You can use asterisk in place of optional width and precision specifiers. And set them as arguments
double myDouble = 123.456789;
int width = 10;
int precision = 6;
NSString *s = [NSString stringWithFormat:#"%*.*g", width, precision, myDouble];
If you follow the links in the documentation for stringWithFormat you will discover the IEEE printf specification which describes the formats supported. That tells you that a field width or precision can be an * to indicate the actual value is supplied an an int argument, so what you want is:
NSString *myString = [NSString stringWithFormat:#"%.*g", intPrecision, myDouble];
double myDouble = 123.456789;
int precision = 4;
NSString *myString = [NSString stringWithFormat:#"%.*f", precision, myDouble];
NSLog(#"myString: '%#'", myString);
NSLog output:
myString: '123.4567'
This is by no means an optimal way of doing it, but it is a way.
You can do it in multiple steps
NSString *val = [NSString stringWithFormat: #"%d", 4];
NSString *head = [#"%." stringByAppendingString: val];
NSString *format = [head stringByAppendingString: #"g"];
NSString *result = [NSString stringWithFormat: format, 123.456789];
Or if you're really adventurous (for the sake of readability, don't EVER do this):
NSString *result = [NSString stringWithFormat: [[#"%." stringByAppendingString: [NSString stringWithFormat: #"%d", 4]] stringByAppendingString: #"g"], 123.456789];

Simple int to NSString conversion as in Java?

Is there any simple way how to initialize String in Objective-C with int such as in Java:
String myStr = 42 + "";
or I have to do
[NSString stringWithFormat:#"%d", 42];
everytime?
You could also use the NSNumber class for that:
NSNumber *number = [[NSNumber alloc] initWithInteger: val];
NSString *string = [number stringValue];
Perhaps not shorter, but it could be eventually faster.
Also you could create as said a helper method, than you wouldn't have to use more code than with the stringWithFormat: method.
Yes you have to do
[NSString stringWithFormat:#"%d", 42];
for Integer to string conversion.
Using a constant, like 42 in your example, you can write
NSString *myString = #"42";
Using a variable or expression, you can write
[NSString stringWithFormat:#"%d", myValue];

NSNumberFormatter leading 0's and decimals

Is there any way to format an NSNumber with leading 0's and decimals? For example, I need to have the ability to write 4.5 as well as 000. Currently I have it where it will allow decimals, but not leading 0's.
NSNumberFormatter *f = [[NSNumberFormatter alloc] init];
f.numberStyle = NSNumberFormatterNoStyle;
NSString *myString = [f numberFromString:#"4.5"];
NSLog(#"myString: %#",myString);
NSString *myOtherString = [f numberFromString:#"000"];
NSLog(#"myOtherString:%#",myOtherString);
The output from above would be: 'myString:4.5' and 'myOtherString:0'. I need to be able to do both '4.5' and '000' as output.
I have looked at Apple's "Data Formatting Guide" without much success.
Note that [f numberFromString:#"4.5"] returns an NSNumber* not a NSString*
You want something like this:
NSNumberFormatter *f = [[NSNumberFormatter alloc] init];
f.numberStyle = NSNumberFormatterNoStyle;
NSNumber *myNumber;
NSString *myString;
myNumber = [f numberFromString:#"4.5"];
[f setNumberStyle:kCFNumberFormatterDecimalStyle];
myString = [f stringFromNumber:myNumber];
NSLog(#"myString: %#",myString);
myNumber = [f numberFromString:#"000"]; // Note that the extra zeros are useless
[f setFormatWidth:3];
[f setPaddingCharacter:#"0"];
myString = [f stringFromNumber:myNumber];
NSLog(#"myString: %#",myString);
NSLog output:
myString: 4.5
myString: 000
If you don't have strings to start with just create number like:
myNumber = [NSNumber numberWithFloat:4.5];
myNumber = [NSNumber numberWithInt:0];
Or just use standard formatting:
myString = [NSString stringWithFormat:#"%.1f", [myNumber floatValue]];
myString = [NSString stringWithFormat:#"%03d", [myNumber intValue]];
Or if you don't need an NSNumber representation just use standard formatting :
myString = [NSString stringWithFormat:#"%.1f", 4.5];
myString = [NSString stringWithFormat:#"%03d", 0];
You could try something like:
NSString *myString = [NSString stringWithFormat:#"%03f", [myNSNumber floatValue]];
This, following the printf format, will print your number forcing at least 3 digits to be printed and padding with '0's any empty space.
How about this as a variation on theme for the 000's
NSNumber *myNumber;
NSString *myString =#"000" ;
NSString * myStringResult;
NSNumberFormatter *f = [[NSNumberFormatter alloc] init];
f.numberStyle = NSNumberFormatterNoStyle;
[f setHasThousandSeparators:FALSE]; //-- remove seperator
[f setMinimumIntegerDigits:[myString length ]]; //-- set minimum number of digits to display using the string length.
myNumber = [f numberFromString:myString];
myStringResult = [f stringFromNumber:myNumber];
NSLog(#"myStringResult: %#",myStringResult);
Since this is asked often and Apple's docs suck, this is the answer that people will be looking for. The link below has two solutions. One using NSString stringWithFormat: and the other using NSNumberFormatter.
https://stackoverflow.com/a/11131497/1058199

Objective-c convert NSString into NSInteger

I've got this little problem. When I have a string "3 568 030" and I use [myString intValue]; it gives me result just 3, the problem is I want to convert the whole number into int/nsinteger. The string always contains just the number if that's any help. I tried using replaceoccurencesofstring (or what is the name) and it somehow didn't work...Thanks
Do:
NSString *str = #"3 568 030";
int aValue = [[str stringByReplacingOccurrencesOfString:#" " withString:#""] intValue];
NSLog(#"%d", aValue);
output
3568030
That is because of the spaces on your string you will have to remove the whitespaces first like this:
NSString *trimmedString = [myString stringByReplacingOccurrencesOfString:#" " withString:#""];
NSInteger *value = [trimmedString intValue];
My guess is that you're using stringByReplacingOccurencesOfString:: wrongly.
//Remove spaces.
myString = [myString stringByReplacingOccurencesOfString:#" " withString #""];
int myNumber = [myString intValue];
First, remove all the whitespaces in your original string using :
NSString *trimmedString = [yourOriginalString stringByTrimmingCharactersInSet:
[NSCharacterSet whitespaceAndNewlineCharacterSet]];
Then, you can convert it to an int/NSInteger. beware: using [myString intValue] will cast your string to an int, but [myString integerValue] will cast it to a NSInteger.
NSNumberFormatter * f = [[NSNumberFormatter alloc] init];
[f setNumberStyle:NSNumberFormatterDecimalStyle];
NSNumber * myNumber = [f numberFromString:#"42"];
[f release];

How to parse strings in Objective C

Can someone help me to extract int timestamp value from this string "/Date(1242597600000)/" in Objective C
I would like to get 1242597600000.
Thx
One simple method:
NSString *timestampString = #"\/Date(1242597600000)\/";
NSArray *components = [timestampString componentsSeparatedByString:#"("];
NSString *afterOpenBracket = [components objectAtIndex:1];
components = [afterOpenBracket componentsSeparatedByString:#")"];
NSString *numberString = [components objectAtIndex:0];
long timeStamp = [numberString longValue];
Alternatively if you know the string will always be the same length and format, you could use:
NSString *numberString = [timestampString substringWithRange:NSMakeRange(7,13)];
And another method:
NSRange openBracket = [timestampString rangeOfString:#"("];
NSRange closeBracket = [timestampString rangeOfString:#")"];
NSRange numberRange = NSMakeRange(openBracket.location + 1, closeBracket.location - openBracket.location - 1);
NSString *numberString = [timestampString substringWithRange:numberRange];
There's more than one way to do it. Here's a suggestion using an NSScanner;
NSString *dateString = #"\/Date(1242597600000)\/";
NSScanner *dateScanner = [NSScanner scannerWithString:dateString];
NSInteger timestamp;
if (!([dateScanner scanInteger:&timestamp])) {
// scanInteger returns NO if the extraction is unsuccessful
NSLog(#"Unable to extract string");
}
// If no error, then timestamp now contains the extracted numbers.
NSCharacterSet* nonDigits = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
NSString* digitString = [timestampString stringByTrimmingCharactersInSet:nonDigits];
return [digitString longValue];