Retrieve UITextfField values and convert to inches with decimal? - iphone

If I have formatting for a textfield like:
//Formats the textfield based on the pickers.
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
NSString *result = [feetArray objectAtIndex:[feetPicker selectedRowInComponent:0]];
result = [result stringByAppendingFormat:#"%#ft", [feetArray objectAtIndex:[feetPicker selectedRowInComponent:1]]];
result = [result stringByAppendingFormat:#" %#", [inchArray objectAtIndex:[inchesPicker selectedRowInComponent:0]]];
result = [result stringByAppendingFormat:#"%#", [inchArray objectAtIndex:[inchesPicker selectedRowInComponent:1]]];
result = [result stringByAppendingFormat:#" %#in", [fractionArray objectAtIndex:[fractionPicker selectedRowInComponent:0]]];
myTextField.text = result;
}
Which display's in the textfield like 00ft 00 0/16in How can I change that all to inches with decimal? I'll need to take the ft, and multiply by 12 = variable.Then add that to inches, as well as take my fraction 1/16 and divide that by 16 to get my decimal value and then add that to the inches so it shows like 1234.0625 in order to make my calculation. Can someone help me accomplish this? Thank you in advance!

NSString * theString = RiseTextField.text;
NSString * feetString = [theString substringWithRange:NSMakeRange(0, 2)];
NSString * inchesString = [theString substringWithRange:NSMakeRange(5, 2)];
NSUInteger rangeLength = ([theString length] == 14) ? 1 : 2;
NSString * fractionString = [theString substringWithRange:NSMakeRange(8, rangeLength)];
double totalInInches = [feetString doubleValue] * 12 + [inchesString doubleValue] + [fractionString doubleValue] / 16;

You can easily get the number that you want by doing the calculations with the numbers you have there. Once you've got the actual number, you should use a NSNumberFormatter to present it with the desired amount of decimals and format.
This should solve your problem. Or did you need help converting the strings to numbers so that you can add them together?

Related

I am getting Expected identifier in Xcode

I'm making an app for iPhone using obj-c that finds side lengths and angles for triangles. Part of the app uses the Pythagorean Theorem.
NSNumber *pySidea = [NSNumber numberWithInteger:[[sideA text] integerValue]];
NSNumber *pySideb = [NSNumber numberWithInteger:[[sideB text] integerValue]];
NSNumber *pySidec = [NSNumber numberWithInteger:[[sideC text] integerValue]];
int pyAside = [pySidea intValue];
int pyBside = [pySideb intValue];
int pyCside = [pySidec intValue];
if ([aSide length] = 0) {
NSString *finalAnserc = [sqrtf(powf(pyAside, 2) + powf(pyBside, 2))];
sideCstring = #"_anserSidec";
}
sideA, sideB and sideC are the sides of a triangle using a text field. I don't get an error for any part except
if ([aSide length] = 0) {
NSString *finalAnserc = [sqrtf(powf(pyAside, 2) + powf(pyBside, 2))];
sideCstring = #"_anserSidec";
}
where I get "Expected identifier". Thanks for any help.
This line:
NSString *finalAnserc = [sqrtf(powf(pyAside, 2) + powf(pyBside, 2))];
Seems to be wanting to create a string, but doesn't do anything except some arithmetic inside square brackets, which isn't valid syntax. I think you want something like:
float answer = sqrtf(powf(pyAside, 2) + powf(pyBside, 2));
NSString *finalAnswer = [[NSNumber numberWithFloat:answer] stringValue];
Calling powf() to square a number is a bit heavy-handed, too. You could just write:
float answer = sqrtf(pyAside*pyAside + pyBside*pyBside);
As Nithin notes in his answer, you have a logical error with your if statement too - you want to be using == probably.
Check your 'if' condition , it should be if([aSide length] == 0)
Remember two equal (=) signs...

How can I split up GPS coordinate in Objective C?

I need to extract the different components from a GPS coordinate string. So for example:
+30° 18' 12" N // pull out 30, 18 & 12
or
+10° 11' 1" E // pull out 10, 11 & 1
or
-3° 1' 2" S // pull out -3, 1 & 2
or
-7° 12' 2" W // pull out -7, 12 & 2
I have had a look around online and I notice there is the NSRegularExpression. I was wondering if it's possible to use this in some way? I have also had a look at the documentation provided and I have tried to put together a regex to pull out the different parts. This is what I came up with:
('+'|'-')$n°\s$n'\s$n"\s(N|E|S|W)
I'm not really sure if this is correct or not, I'm also unclear on how to use it since there aren't many tutorials/example around. Please could someone help me out? If there is a better way of doing this rather than using NSRegularExpression I'm open to it, however as far as I'm aware objective c does't have any built in regex support.
RegExps are an overkill, IMHO. Use [NSString componentsSeparatedByString:] with space as the separator to split the string into parts, then [NSString intValue] to tease the numeric value of each component except for the last one.
Using NSScanner:
NSScanner *scanner;
NSCharacterSet *numbersSet = [NSCharacterSet characterSetWithCharactersInString:#" °'"];
int degrees;
int minutes;
int seconds;
NSString *string = #" -7° 12' 2\" W";
scanner = [NSScanner scannerWithString:string];
[scanner setCharactersToBeSkipped:numbersSet];
[scanner scanInt:&degrees];
[scanner scanInt:&minutes];
[scanner scanInt:&seconds];
NSLog(#"degrees: %i, minutes: %i, seconds: %i", degrees, minutes, seconds);
NSLog Output:
degrees: -7, minutes: 12, seconds: 2
RE's overkill (Seva)? How about objects? ;-)
NSString *coords = #"+30° 18' 12\" N";
int deg, sec, min;
char dir;
if(sscanf([coords UTF8String], "%d° %d' %d\" %c", &deg, &min, &sec, &dir) != 4)
NSLog(#"Bad format: %#\n", coords);
else
NSLog(#"Parsed %d deg, %d min, %d sec, dir %c\n", deg, min, sec, dir);
Whether you like this depends on your view of dropping into C, but it is direct and simple.
NSMutableArray *newCoords = [[NSMutableArray alloc] init];
NSArray *t = [oldCoords componentsSeparatedByString: #" "];
[newCoords addObject: [[t objectAtIndex: 0] intValue];
[newCoords addObject: [[t objectAtIndex: 1] intValue];
[newCoords addObject: [[t objectAtIndex: 2] intValue];
Assuming you had the coordinates given in your post in NSString oldCoords, this would result in an NSMutableArray called newCoords which would contain the three pieces of data you need.
The re you need is: #"([+-]?[0-9]+)"
Here is example code:
NSString *string;
NSString *pattern;
NSRegularExpression *regex;
NSArray *matches;
pattern = #"([+-]?[0-9]+)";
regex = [NSRegularExpression
regularExpressionWithPattern:pattern
options:NSRegularExpressionCaseInsensitive
error:nil];
string = #" -7° 12' 2\" W";
NSLog(#"%#", string);
matches = [regex matchesInString:string options:0 range:NSMakeRange(0, [string length])];
degrees = [[string substringWithRange:[[matches objectAtIndex:0] range]] intValue];
minutes = [[string substringWithRange:[[matches objectAtIndex:1] range]] intValue];
seconds = [[string substringWithRange:[[matches objectAtIndex:2] range]] intValue];
NSLog(#"degrees: %i, minutes: %i, seconds: %i", degrees, minutes, seconds);
NSLog output:
degrees: -7, minutes: 12, seconds: 2

Convert string fraction to decimal

I have a plist file that I am reading out a measurement, but some of the measurements are fractions such as 6 3/8". I formatted them that way because it's easier to find that on a tape measure than it is to find 6.375". My problem is now I want to do a conversion to metric on the fly and it isn't reading in the fraction part of the number. My current code is this.
cutoutLabel.text = [NSString stringWithFormat:#"%.2f mm. %#", [[[sizeDict valueForKey:Sub_Size] objectForKey:#"Cutout Dimensions"]floatValue] * 25.4, [temp objectAtIndex:2]];
Thanks.
That's what I ended up doing.
NSArray *temp = [[[sizeDict valueForKey:Sub_Size] objectForKey:#"Cutout Dimensions"] componentsSeparatedByString:#" "];
if ([temp count] > 2) {
NSArray *fraction = [[temp objectAtIndex:1]componentsSeparatedByString:#"/"];
convertedFraction = [[fraction objectAtIndex:0]floatValue]/[[fraction objectAtIndex:1]floatValue];
}
You can get the numerator and denominator as follows:
NSRange slashPos = [fraction.text rangeOfString:#"/"];
NSString * numerator = [fraction.text substringToIndex:slashPos.location];
NSString * denominator = [fraction.text substringFromIndex:slashPos.location+1];
You should take more care than this,
check that your range is of length 1 and make sure that the string has characters after the "/" character. But if you know you are feeding this code a fraction string it should work in your case
The idea is in place, but you will also need to apply the same logic first to separate the whole number from you fraction. Apply the same logic, searching for a #" " and then find the numerator and denominator
Building on Ian's answer and trying to be a little more complete (since his example was for a whole number and fractional part with an inch character (6 3/8"), I suggest the following method (it also works if there are spaces before the whole number:
// Convert a string consisting of a whole and fractional value into a decimal number
-(float) getFloatValueFromString: (NSString *) stringValue {
// The input string value has a format similar to 2 1/4". Need to remove the inch (") character and
// everything after it.
NSRange found = [stringValue rangeOfString: #"\""]; // look for the occurrence of the " character
if (found.location != NSNotFound) {
// There is a " character. Get the substring up to the "\"" character
stringValue = [stringValue substringToIndex: found.location];
}
// Now the input format looks something like 2 1/4. Need to convert this to a float value
NSArray *temp = [stringValue componentsSeparatedByString:#" "];
float convertedFraction = 0;
float wholeNumber = 0;
for (int i=0; i<[temp count]; i++) {
if ([[temp objectAtIndex:i] isEqualToString:#""]) {
continue;
}
NSArray *fraction = [[temp objectAtIndex:i]componentsSeparatedByString:#"/"];
if ([fraction count] > 1) {
convertedFraction = [[fraction objectAtIndex:0]floatValue]/[[fraction objectAtIndex:1]floatValue];
}
else if ([fraction count] == 1) {
wholeNumber = [[fraction objectAtIndex:0] floatValue];
}
}
convertedFraction += wholeNumber;
return convertedFraction;
}

iPhone NSNumberFormatter for less than 1 value

I have a floating point value
i.e. 0.0467
Want have a string
05
how can get it? Excluding the decimal point (.).
More precisely, if I have a floating point number, I want to divide it to integral and decimal, preferably into two string parts.
By following this, you will get desired result.
float floatValue = 0.0467;
NSString *str = [NSString stringWithFormat:#"%.2f", floatValue];
str = [str stringByReplacingCharactersInRange:NSMakeRange(0, 2) withString:#""];
NSLog(#"%#", str); // Result will be: 05
fDecimal = 0.04567;
NSString * strDecimal = [NSString stringWithFormat:#"%0.2f", fDecimal];
NSString * strDecimalPart = [strDecimal substringWithRange:NSMakeRange(2, 2)];
The setting you are looking for is called fraction digits:
NSNumberFormatter* f = [[[NSNumberFormatter alloc] init] autorelease;
[f setMaximumFractionDigits:2];
Optionally you can use -[NSNumberFormatter setRoundingMode:] to specify how rounding should be done.

Help with UISlider

With my UISlider, if my value 'tipPercentage' gets to 10 or more, the label 'costWithTipLabel' gets set back to the textField's 'costWithoutTip' value starting with a 10% tip increase.
I would really appreciate it if you could take a look at my code and let me know of the problem causing this.
Thanks in advanced.
- (IBAction)aSliderChanged:(id)sender {
UISlider *slider = (UISlider *)sender;
if (slider == tipslide) {
NSString *tip = [NSString stringWithFormat:#"%.f", slider.value * 100];
float tipPercentage = [tip floatValue];
NSString *multiplier = [NSString stringWithFormat:#"1.%.f", tipPercentage];
[costWithTipLabel setText:[NSString stringWithFormat:#"%.2f", [[costWithoutTip text] floatValue] * [multiplier floatValue]]];
[tipTextLabel setText:[[NSString stringWithFormat:#"Tip (%.f", slider.value *100]stringByAppendingString:#"%):"]];
}
else if (slider == peopleslide) {
NSString *p = [NSString stringWithFormat:#"%.f", slider.value*10];
float numOfPeople = [p floatValue];
[numberOfPeopleTextLabel setText:[NSString stringWithFormat:#"Each (%.f):", numOfPeople]];
[numberOfPeopleLabel setText:[NSString stringWithFormat:#"%.2f", [[costWithTipLabel text] floatValue]/numOfPeople]];
}
[totalBillCost setText:[NSString stringWithFormat:#"%.2f", [[costWithTipLabel text] floatValue]]];
}
I expect it has to do with unexpected formatting of your strings. I suggest you break your stringWithFormat assignments into multiple simple (non-nested) statements, and then NSLog your values using as generic a format (%f) as possible. Then you should be able to track down where the problem is.