Unexpected result from "stringWithFormat:" - iphone

What would be the expected result from the following Objective C code?
int intValue = 1;
NSString *string = [NSString stringWithFormat:#"%+02d", intValue];
I thought the value of string would be "+01", it turns out to be "+1". Somehow "0" in format string "+01" is ignored. Change code to:
int intValue = 1;
NSString *string = [NSString stringWithFormat:#"%02d", intValue];
the value of string is now "01". It does generate the leading "0". However, if intValue is negative, as in:
int intValue = -1;
NSString *string = [NSString stringWithFormat:#"%02d", intValue];
the value of string becomes "-1", not "-01".
Did I miss anything? Or is this a known issue? What would be the recommended workaround?
Thanks in advance.

#Mark Byers is correct in his comment. Specifying '0' pads the significant digits with '0' with respect to the sign '+/-'. Instead of '0' use dot '.' which pads the significant digits with '0' irrespective of the sign.
[... stringWithFormat:#"%+.2d", 1]; // Result is #"+01"
[... stringWithFormat:#"%.2d", -1]; // Result is #"-01"

NSString *string = [NSString stringWithFormat:#"+0%d", intValue];
NSString *string = [NSString stringWithFormat:#"-0%d", intValue];

Related

Convert NSString to Int

I try to convert NSString to int,Result dpPoint:0, I want dpPoint:2
dpPointStr = [NSString stringWithFormat:#"%#",[verifyRow valueForKey:#"default_point"]];
NSLog(#"dpPointStr:%#",dpPointStr); //Result dpPointStr:2
int dpPoint = [dpPointStr intValue];
NSLog(#"dpPoint:%i",dpPoint); //Result dpPoint:0
In your case, if value is in the beginning/end of the string you can try this:
int val = [[dpPointStr stringByTrimmingCharactersInSet:[[NSCharacterSet decimalDigitCharacterSet] invertedSet]] intValue];
int str_len = [yourStr length]; char tmp[str_len];
[NSString getCString:tmp maxLength:str_len encoding:UTF8Encoding];
int dpPoint = atoi(tmp);
Don't forget to include this: #include
I think this should work just fine.
Also, I think you can fix this by taking the intValue from the:
[verifyRow valueForKey:#"default_point"];
To be consistent with Apple use NSInteger instead, or even better NSNumber for the valueForKey statement and then NSInteger.
Convert NSString to integer
NSString *sampleText = #"5";
int numValue = [sampleText intValue];
NSLog(#"Integer Value: %d", numValue);

Replace a character in a String iPhone

I want to replace a single character at a particular position in a string.
Example
String: 123-456-7890
Desired Output: 123-406-7890 (Replacing 5 at fifth position with 0)
https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/
visit here and read all about string
Use stringByReplacingCharactersInRange:withString:, forming the NSRange variable to indicate the 5th position.
NSString *phoneNumber = #"123-456-7890";
NSString *newString = [phoneNumber stringByReplacingCharactersInRange:NSMakeRange(5, 1) withString:#"0"];
NSLog(#"%#", newString);
Output: 123-406-7890
Read all about NSString.
for replacing string there are lots of way:
NSString *str = [yourString stringByReplacingOccuranceOfString:#"5" withString:#"0"];
second way first get range of string like:
NSRange range = [yourSting rangeOfString:#"5"];
NSString *first = [yourString substringToIndex:range.location];
NSString *second = [yourString substringFromIndex:range.location+range.length];
NSString *yourNewStr = [NSString stringWithFormat:#"%#0%#",first,second];
Tere are lots of other using string operation but First one is best in that.
Get the range (i.e. index) of first occurrence of the substring.
Then replace at that range with your desired replace value.
NSString *originalString = #"123 456 789";
NSRange r = [originalString rangeOfString:#"5"];
NSString *newString = [originalString stringByReplacingCharactersInRange:r withString:#"0"];
If you want to actually replace the 5th character rather than just any 5 you need to make a range first.
NSRange range = NSMakeRange(5, 1);
NSString *newString = [initialString stringByReplacingCharactersInRange:range withString:#"0"];
Edit: Corrected make range length
you can use :-
NSString *replacechar = #"0";
NSString *newString= [String stringByReplacingCharactersInRange:NSMakeRange(5,1) withString:replacechar];

Add character or special character in NString?

I have an NSString *string=#"606" and I want to add a ":" colon after two digits.
The output should look like this: 6:06
It this is possible?
Help would be appropriated.
Thank you very much.
You can add the column between the hours and the minutes like this:
NSString *string = #"606";
NSString *result = [string stringByReplacingCharactersInRange:NSMakeRange(string.length-2, 0) withString:#":"];
NSLog(#"%#", result);
This will give the following results
#"606" => #"6:06"
#"1200" => #"12:00"
#"1406" => #"14:30"
Note: This will only work if the string has 3 or 4 characters, but this is the case according to your question.
Because you do not have two separate objects for hours and minutes, use:
NSString *newTimeString, *hour, *minute;
NSUInteger length = [timeString length];
if (length == 3)
{
hour = [timeString substringToIndex:1];
minute = [timeString substringFromIndex:2];
}
else
{
hour = [timeString substringToIndex:2];
minute = [timeString substringFromIndex:3];
}
newTimeString = [NSString stringWithFormat:#"%#:%#", hour, minute];
I used a long version to illustrate the concept. Basically, use the length of the original string (timeString) to extract the time components and combine them with a colon.
Will it be 2 digits no matter what? Otherwise you could build your custom string from parameters.
NSString *string = [NSString stringWithFormat:#"%#:%#", hours, minutes];
UPDATE
If you just need to add a colon after 1 char, you can do it this way. Although I would suggest finding a safer method as this could be inaccurate if you have a double digit hour.
NSString *hour = [NSString substringToIndex:1]; // double check the index
NSString *min = [NSString substringFromIndex:1]; // double check the index
NSString *time = [NSString stringWithFormat:#"%#:%#", hour, min];
Hopefully this will help.

Very strange - %i didn't work for integer, %d did?

It was very strange when I saw this on debugging my application.
int iTag = btnTemp.tag; //btnTemp.tag = 1
NSString *strFriendID = [NSString stringWithFormat:#"%i",iTag];
gave me strFriendID as empty string.
int iTag = btnTemp.tag; //btnTemp.tag = 1
NSString *strFriendID = [NSString stringWithFormat:#"%d",iTag];
gave me strFriendID as 1.
How can this happen?
i don't know why you get this answer, but when i read your question i tried in my project but i get the value
UIButton *btnTemp = [[UIButton buttonWithType:UIButtonTypeCustom] retain];
btnTemp.tag = 1;
int iTag = btnTemp.tag; //btnTemp.tag = 1
NSString *strFriendID = [NSString stringWithFormat:#"%i",iTag];
NSLog(#"Str %#", strFriendID);
NSString *strFriendID1 = [NSString stringWithFormat:#"%d",iTag];
NSLog(#"Str %#", strFriendID1);
Out Put
2012-03-26 10:32:02.899 Leaves[506:f803] Str 1
2012-03-26 10:32:02.901 Leaves[506:f803] Str 1
both gives me 1
As per Apple:
%d, %D and %i all represent Signed 32-bit integers.
So yeah it's weird that %i didn't work but it's not so weird that %d worked.
Perhaps btnTemp.tag was null at that point

String to double

I hope you can help me out with this 'small' problem. I want to convert a string to a double/float.
NSString *stringValue = #"1235";
priceLabel.text = [NSString stringWithFormat:#"%d",[stringValue doubleValue]/(double)100.00];
I was hoping this to set the priceLabel to 12,35 but I get some weird long string meaning nothing to me.
I have tried:
priceLabel.text = [NSString stringWithFormat:#"%d",[stringValue intValue]/(double)100.00];
priceLabel.text = [NSString stringWithFormat:#"%d",[stringValue doubleValue]/100];
but all without success.
This is how to convert an NSString to a double
double myDouble = [myString doubleValue];
You have to use %f to show float/double value.
then %.2f means 2digits after dot
NSString *stringValue = #"1235";
NSString *str = [NSString stringWithFormat:#"%.2f",[stringValue doubleValue]/(double)100.00];
NSLog(#"str : %# \n\n",s);
priceLabel.text = str;
OUTPUT:
str : 12.35
I think you have the wrong format string. Where you have:
[NSString stringWithFormat:#"%d", ...];
You should really have:
[NSString stringWithFormat:#"%f", ...];
%d is used for integer values. But you're trying to display a floating point number (%f).