Convert float to NSString using custom format? ("xx:yy") - ios

I'm getting a JSON string back from a web service I'm using, one of the items is a float, which is formatted like this: "1.2".
But I actually want to make it show like a time number, so like this: "01:20".
What would be the easiest way of doing this?
I thought about converting the float to a string and then splitting it into 2 pieces
timeValue = [NSString stringWithFormat:#"%.2f", timeValue];
NSArray *tmpArr = [timeValue componentsSeparatedByString:#"."];
NSString *tmpFirst = (NSString *)[tmpArr objectAtIndex:0];
NSString *tmpSecond = (NSString *)[tmpArr objectAtIndex:0];
But somehow when I convert it, it returns me a negative number
NSLog(#"timeValue: %#", timeValue);
timeValue: -1.99

I think the problem is in this line.
timeValue = [NSString stringWithFormat:#"%.2f", timeValue];
I think timeValue is of type NSString if not then why are you using same variable twice.
It should be like
timeValueString = [NSString stringWithFormat:#"%.2f", timeValueFloat];

Related

present NSString as a line of elements

I have an NSString that hold data (actually that could be presented an NSArray). and i want to output that on a label.
In NSLog my NSString output is:
(
"cristian_camino",
"daddu_02",
"_ukendt_babe_",
"imurtaza.zoeb"
)
What i want is, to present it like :"cristian_camino","daddu_02","_ukendt_babe_","imurtaza.zoeb"
In a single line.
I could accomplish that turning string to an array and do following: arrayObjectAtIndex.0, arrayObjectAtIndex.1, arrayObjectAtIndex.2, arrayObjectAtIndex.3.
But thats look not good, and that objects may be nil, so i prefer NSString to hold data.
So, how could i write it in a single lane?
UPDATE:
There is the method i want to use to set text for UILabel:
-(void)setLikeLabelText:(UILabel*)label{
//Likes
NSString* likersCount = [self.photosDictionary valueForKeyPath:#"likes.count"];
NSString* likersRecent = [self.photosDictionary valueForKeyPath:#"likes.data.username"];
NSString *textString = [NSString stringWithFormat:#"%# - amount of people like it, recent "likes": %#", likersCount, likersRecent];
label.text = textString;
NSLog(#"text String is %#", textString);
}
valueForKeyPath: returns an NSArray, not an NSString. Whilst you've declared likersCount and likersRecent as instances of NSString, they're actually both arrays of values. You should be able to do something like the following to construct a string:
NSArray* likersRecent = [self.photosDictionary valueForKeyPath:#"likes.data.username"];
NSString *joined = [likersRecent componentsJoinedByString:#"\", \""];
NSString *result = [NSString stringWithFormat:#"\"%#\"", joined];
NSLog(#"Result: %#", result);
componentsJoinedByString: will join the elements of the array with ", ", and then the stringWithFormat call will add a " at the beginning and end.
The statement is incorrect, the internal quote marks (" that you want to display) need to be escaped:
NSString *textString = [NSString stringWithFormat:#"%# - amount of people like it, recent \"likes\": %#", likersCount, likersRecent];
If somebody curious how i fix it, there it is:
for (int i =0; i < [likersRecent count]; i++){
stringOfLikers = [stringOfLikers stringByAppendingString:[NSString stringWithFormat:#" %#", [likersRecent objectAtIndex:i]]];
}
Not using commas or dots though.

iOS: Create String from Variable and string combined

I need to concatenate a string and a variable together - I kind of find lots of examples of adding a string prior to a variable but not the other way round - how do I do this?
NSString *theImage = [[self.detailItem valueForKey:#" resimagefiletitle"] description], #"'add on the end";
Something like this:
NSString *theImage = [NSString stringWithFormat:#"%# %#",[self.detailItem valueForKey:#" resimagefiletitle"], #"'add on the end"];
Or:
NSString *theImage = [NSString stringWithFormat:#"%# add on the end",[self.detailItem valueForKey:#" resimagefiletitle"]];
Try this
NSString *theImage = [NSString stringWithFormat:#"%# '>",[[self.detailItem valueForKey:#"resimagefiletitle"] description]];
Here I am considering [[self.detailItem valueForKey:#"resimagefiletitle"] description] gives NSString
We can concat diffrent type of datatypes into string by mention the format for it.
like if your want to concat two or more strings together then you can use the following code:
NSString *NewString = [NSString stringWithFormat:#"%#%#",#"This Is",#"way to concate string"];
and if your want concat integer value then you can mention the data format for it "%i".
eg:
int OutOf = 150;
NSString *NewString = [NSString stringWithFormat:#"%#%i",#"I got 100 out of ",OutOf];
this may help you.

Conversion issue from NSNumber to NSString

I'm parsing data from a JSON webservice and adding it to the database so when I insert an int, I have to convert it to NSNumber in this way it's working fine: 24521478
NSString *telephone = [NSString stringWithFormat:#"%#",[user objectForKey:#"telephone"]];
int telephoneInt = [telephone intValue];
NSNumber *telephoneNumber = [NSNumber numberWithInt:telephoneInt];
patient.telephone = telephoneNumber;
but when I want to display it and convert the NSNumber to NSString I'm getting wrong numbers: -30197
NSString *telephoneString = [NSString stringWithFormat:#"%d", [user.telephone intValue], nil];
labelTelephone.text =telephoneString ;
Can someone explain this?
NSNumber comes with dedicated methods for each data type.If you want to convert NSNumber to NSString use:
NSString *telephoneString = [user.telephone stringValue];
The issue may coming because of the data type you used for the variable patient.telephone
If you have control over the web service, then you should return the telephone number as string in the JSON
Reasons
if the telephone number begin with zero then the NSNumber will remove that zero as it has no value (ex: 00123456789 will be 123456789 which will wrong data)
You will not be able to display the telephone number is a user friendly way by adding "+" and "-" (ex: +123-456-789)
You really should make the json return the number as string if you have a control over that

iOS finding string within a string

Hello everyone I am trying find a string inside a string
lets say I have a string:
word1/word2/word3
I want to find the word from the end of the string to the last "/"
so what I will get from that string is:
Word3
How do I do that?
Thanks!
You are looking for the componentsSeparatedByString: method
NSString *originalString = #"word1/word2/word3";
NSArray *separatedArray = [originalString componentsSeparatedByString:#"/"];
NSString *lastObject = [separatedArray lastObject]; //word3
once check this one By using this one you'l get last pathcomponent values,
NSString* theFileName = #"how /are / you ";
NSString *str1=[theFileName lastPathComponent];
NSLog(#"%#",str1);
By using lastPathComponent you'l get the last path component directly no need to take array for separate the string.
you must use NSScanner class to split substring.
check this.
Objective C: How to extract part of a String (e.g. start with '#')
NSString *string = #"word1/word2/word3"
NSArray *arr = [string componentsSeperatedByString:#"/"];
NSSting *str = [arr lastObject];
You can find it also with this way:
NSMutableString *string=[NSMutableString stringWithString:#"word1/word2/word3"];
NSRange range=[string rangeOfString:#"/" options:NSBackwardsSearch];
NSString *subString=[string substringFromIndex:range.location+1];
NSRegularExpression or NSString rangeOfString:options:range:locale: (with options to search backwards).
The answer really depends on exactly what the input string will contain (how consistent it is).

Removing last characters of NSString until it hits a separator

I've got a string that shows the stock amount using "-" as separators.
It's built up like this: localStock-wareHouseStock-supplierStock
Now I want to update the supplierStock at the end of the string, but as you can see in the code below it goes wrong when the original string returns more than a single-space value (such as 20).
Is there a way to remove all characters until the last "-" (or remove characters after the second "-")?
NSMutableString *string1 = [NSMutableString stringWithString: p1.colorStock];
NSLog(#"string1: %#",string1);
NSString *newString = [string1 substringToIndex:[string1 length]-2];
NSLog(#"newString: %#",newString);
NSString *colorStock = [NSString stringWithFormat:#"%#-%#",newString,p2.supplierStock];
NSLog(#"colorstock: %#",colorStock);
p1.colorStock = colorStock;
NSLog1
string1: 0-0-0
newString: 0-0
colorstock: 0-0-20
NSLog2
string1: 0-0-20
newString: 0-0-
colorstock: 0-0--20
EDIT: Got it working thanks to Srikar!
NSString *string1 = [NSString stringWithString: p1.colorStock];
NSLog(#"string1: %#",string1);
NSString *finalString = [string1 stringByReplacingOccurrencesOfString:[[string1 componentsSeparatedByString:#"-"] lastObject] withString:p2.supplierStock.stringValue];
NSLog(#"finalString: %#",finalString);
p1.colorStock = finalString;
Why not use componentsSeparatedByString followed by lastObject ?
NSString *supplierStock = [[string1 componentsSeparatedByString:#"-"] lastObject];
The above works if the "stock amount" is always in sets of 3's separated by a "-". Also since you always want supplierStock, lastObject is perfect for your needs.
Of course after splitting string1 with - you get a NSArray instance and you can access the individual components using objectAtIndex:index. So if you want localStock you can get by
NSString *localStock = [[string1 componentsSeparatedByString:#"-"] objectAtIndex:0];
I would suggest splitting the string into the 3 parts using [NSString componentsSeparatedByString:#"-"] and then building it back up again:
NSArray *components = [p1.colorStock componentsSeparatedByString:#"-"];
p1.colorStock = [NSString stringWithFormat:#"%#-%#-%#",
[components objectAtIndex:0],
[components objectAtIndex:1],
p2.supplierStock];
With a string that looks like
NSString *myString = #"Hello-World";
you can separate it with the componentsSeparatedByString: method of the NSString object as
NSArray *myWords = [myString componentsSeparatedByString:#"-"];
The myWords - array will then contain the two NSString objects Hello and World.
To access the strings:
NSString *theHelloString = [myWords objectAtIndex:0];
NSString *theWorldString = [myWords objectAtIndex:1];
Hope it helps!
None of these examples show how to do this if you are unaware of how many of these separator occurrences you're going to have in the original string.
Here's what I believe the correct the correct code should be for dismantling the original string and rebuilding it until you reach the final separator, regardless of how many separators it contains.
NSString *seperator = #" ";
NSString *everythingBeforeLastSeperator;
NSArray *stringComponents = [originalString componentsSeparatedByString:seperator];
if (stringComponents.count!=0) {
everythingBeforeLastSeperator = [stringComponents objectAtIndex:0];
for (int a = 1 ; a < (stringComponents.count - 1) ; a++) {
everythingBeforeLastSeperator = [NSString stringWithFormat:#"%#%#%#", everythingBeforeLastSeperator, seperator, [stringComponents objectAtIndex:a]];
}
}
return everythingBeforeLastSeperator;

Resources