how to convert uitextfield integer into string - ios

I am new to iOS. I need to convert textfield integer value into string. I created textfield name as value1 and string as str1.
str1 = [NSString stringWithFormat:#"%d", value1];

By default, UITextField returns a NSString value.
So you can get any value like this :
NSString *str1 = value1.text;
As simple as that, but if you want to convert it to Int then,
int strInt = str1.intValue;
NSInteger strInteger = str1.integerValue;
If want to converts to a Double value,
double strDouble = str1.doubleValue;
CGFloat strCGFloat = str1.doubleValue;
And yes, if you don't need to perform anything on str1 then you shouldn't need to create an instance, you can directly convert it like this.
int strInt = value1.text.intValue;
NSInteger strInteger = value1.text.intValue;

Related

Get one digit after decimal point iOS Objective C

I am trying to get one digit after decimal and store it as double.
For eg : -
float A = 146.908295;
NSString * string = [NSString stringWithFormat:#"%0.01f",A]; // op 146.9
double B = [string doubleValue]; // op 146.900000
i want output as 146.9 in double or float form..,before duplicating or downvoting make sure the answer to this output is given..
Thanks
Edited:-
NSString * str = [NSString stringWithFormat:#"%0.01f",currentAngle];
tempCurrentAngle = [str doubleValue];;
tempCurrentAngle = tempCurrentAngle - 135.0;
if (tempCurrentAngle == 8.7) {
NSLog(#"DONE ");
}
here currentAngle is coming from continueTrackingWithTouch method, which will be in float..here it does not enter in if loop even when tempCurrentAngle value changes to 8.700000 .
You can compare string values instead of double like,
double currentAngle = 143.7; // I have taken static values for demo.
double tempCurrentAngle = 0.0;
NSString * str = [NSString stringWithFormat:#"%0.01f",currentAngle];
tempCurrentAngle = [str doubleValue];;
tempCurrentAngle = tempCurrentAngle - 135.0;
NSString *strToCompare = [NSString stringWithFormat:#"%0.01f",tempCurrentAngle];
if ([strToCompare isEqualToString:#"8.7"] ) {
NSLog(#"DONE ");
}
If you debug once line by line then you will get idea that why it was not entering in if caluse.
tempCurrentAngle get 143.69999999999999 when you convert str to double then you reduce 135.0 from it so it's value will be 8.6999999999999886 and then you compare it with 8.7 then it will definitely not being equal! but if you convert tempCurrentAngle string with one decimal point then it will be 8.7! so you should compare string values instead of double!

Converting int to NSString

I thought I had nailed converting an int to and NSString a while back, but each time I run my code, the program gets to the following lines and crashes. Can anyone see what I'm doing wrong?
NSString *rssiString = (int)self.selectedBeacon.rssi;
UnitySendMessage("Foo", "RSSIValue", [rssiString UTF8String] );
These lines should take the rssi value (Which is an NSInt) convert it to a string, then pass it to my unity object in a format it can read.
What am I doing wrong?
NSString *rssiString = [NSString stringWithFormat:#"%d", self.selectedBeacon.rssi];
UPDATE: it is important to remember there is no such thing as NSInt. In my snippet I assumed that you meant NSInteger.
If you use 32-bit environment, use this
NSString *rssiString = [NSString stringWithFormat:#"%d", self.selectedBeacon.rssi];
But you cann't use this in 64-bit environment, Because it will give below warning.
Values of type 'NSInteger' should not be used as format arguments; add
an explicit cast to 'long'
So use below code, But below will give warning in 32-bit environment.
NSString *rssiString = [NSString stringWithFormat:#"%ld", self.selectedBeacon.rssi];
If you want to code for both(32-bit & 64-bit) in one line, use below code. Just casting.
NSString *rssiString = [NSString stringWithFormat:#"%ld", (long)self.selectedBeacon.rssi];
I'd like to provide a sweet way to do this job:
//For any numbers.
int iValue;
NSString *sValue = [#(iValue) stringValue];
//Even more concise!
NSString *sValue = #(iValue).stringValue;
NSString *rssiString = [self.selectedBeacon.rssi stringValue];
For simple conversions of basic number values, you can use a technique called casting. A cast forces a value to perform a conversion based on strict rules established for the C language. Most of the rules dictate how conversions between numeric types (e.g., long and short versions of int and float types) are to behave during such conversions.
Specify a cast by placing the desired output data type in parentheses before the original value. For example, the following changes an int to a float:
float myValueAsFloat = (float)myValueAsInt;
One of the rules that could impact you is that when a float or double is cast to an int, the numbers to the right of the decimal (and the decimal) are stripped off. No rounding occurs. You can see how casting works for yourself in Workbench by modifying the runMyCode: method as follows:
- (IBAction)runMyCode:(id)sender {
double a = 12345.6789;
int b = (int)a;
float c = (float)b;
NSLog(#"\ndouble = %f\nint of double = %d\nfloat of int = %f", a, b, c);
}
the console reveals the following log result:
double = 12345.678900
int of double = 12345
float of int = 12345.000000
original link is http://answers.oreilly.com/topic/2508-how-to-convert-objective-c-data-types-within-ios-4-sdk/
If self.selectedBeacon.rssi is an int, and it appears you're interested in providing a char * string to the UnitySendMessage API, you could skip the trip through NSString:
char rssiString[19];
sprintf(rssiString, "%d", self.selectedBeacon.rssi);
UnitySendMessage("Foo", "RSSIValue", rssiString );

Regex get string from string

I have NSString that contain this string :
c&&(b.signature=Rk(c));return ql(a,b)}
The RK can be any two chars.
I try to get the RK from the string with (RegexKitLit):
NSString *functionCode = [dataStr2 stringByMatching:#".signature=(.*?)\(" capture:1L];
and functionCode is always nil.Any idea what wrong?
Don't bother with regular expressions for this. If the format of the string is always the same then you can simply do:
NSString *dataStr2 = #"c&&(b.signature=Rk(c));return ql(a,b)}";
NSString *functionCode = [dataStr2 substringWithRange:NSMakeRange(16, 2)];
If the string is not quite so fixed then base it on the position of the =.
NSString *dataStr2 = #"c&&(b.signature=Rk(c));return ql(a,b)}";
NSRange equalRange = [dataStr2 rangeOfString:#"="];
NSString *functionCode = [dataStr2 substringWithRange:NSMakeRange(equalRange.location + equalRange.length, 2)];

Append to beginning of NSString method

I would like to append NSString A in front of NSString B. Is there a built in method to append to the beginning of a NSString instead of the end of the NSString?
I know that I can use stringWithFormat, but then what is the difference between using stringWithFormat and stringByAppendingString to add text to the end of a NSString?
If you can append to the end of a string, you can prepend to the beginning of the string.
Append
NSString* a = #"A";
NSString* b = #"B";
NSString* result = [a stringByAppendingString:b]; // Prints "AB"
Prepend
NSString* a = #"A";
NSString* b = #"B";
NSString* result = [b stringByAppendingString:a]; // Prints "BA"
Single line solution:
myString = [#"pretext" stringByAppendingString:myString];
You can use stringWithFormat too:
NSString *A = #"ThisIsStringA";
NSString *B = #"ThisIsStringB";
B = [NSString stringWithFormat:#"%#%#",A,B];
stringByAppendingString is an instance method of NSString,
stringWithFormat is a class method of the class NSString.
It's probably worth pointing out that there is no such thing as "appending one string onto another". NSString is immutable.
In every case, you are "creating a new string that consists of one string following another".
It doesn't matter that you put the newly created string back into the same variable.
You are never "adding text to the end of a string".
Here I’ve solution in Swift:
extension String {
// Add prefix only, if there is not such prefix into a string
mutating func addPrefixIfNeeded(_ prefixString: String?) {
guard let stringValue = prefixString, !self.hasPrefix(stringValue) else {
return
}
self = stringValue + self
}
// Add force full prefix, whether there is already such prefix into a string
mutating func addPrefix(_ prefixString: String?) {
guard let stringValue = prefixString else {
return
}
self = stringValue + self
}
}

How to capture last 4 characters from NSString

I am accepting an NSString of random size from a UITextField and passing it over to a method that I am creating that will capture only the last 4 characters entered in the string.
I have looked through NSString Class Reference library and the only real option I have found that looks like it will do what I want it to is
- (void)getCharacters:(unichar *)buffer range:(NSRange)aRange
I have used this once before but with static parameters 'that do not change', But for this implementation I am wanting to use non static parameters that change depending on the size of the string coming in.
So far this is the method I have created which is being passed a NSString from an IBAction else where.
- (void)padString:(NSString *)funcString
{
NSString *myFormattedString = [NSString stringWithFormat:#"%04d",[funcString intValue]]; // if less than 4 then pad string
// NSLog(#"my formatedstring = %#", myFormattedString);
int stringLength = [myFormattedString length]; // captures length of string maybe I can use this on NSRange?
//NSRange MyOneRange = {0, 1}; //<<-------- should I use this? if so how?
}
Use the substringFromIndex method,
OBJ-C:
NSString *trimmedString=[string substringFromIndex:MAX((int)[string length]-4, 0)]; //in case string is less than 4 characters long.
SWIFT:
let trimmedString: String = (s as NSString).substringFromIndex(max(s.length-4,0))
Try This,
NSString *lastFourChar = [yourNewString substringFromIndex:[yourNewString length] - 4];
You can check this function in Swift 5:
func subString(from myString: NSString, length: Int) {
let myNSRange = NSRange(location: myString.length - length, length: length)
print(myString.substring(with: myNSRange))
}
subString(from: "Menaim solved the issue", length: 4) // Output: ssue

Resources