Conversion Fahrenheit to celsius programmatically - iphone

In my project, want to show the weather in fahrenheit first, then if the user wants clickes on conversion, needs to show the weather in celsius. My code is
NSNumber *metric = [[NSUserDefaults standardUserDefaults] objectForKey:#"metric"];
NSLog(#"Metric is %#", metric);
CGFloat aFloat = [speed floatValue];
CGFloat tFloat = [temperature floatValue];
CGFloat tempFloat = (tFloat-30)/2;
NSNumber * p_Number = [NSNumber numberWithFloat:tempFloat];
//Convert mph to kmph
if ([metric boolValue]) {
[windValueLabel setText:[NSString stringWithFormat:#"%.2f kmph", aFloat * 1.6] ];
temperatureLabel.text = [NSString stringWithFormat:#"%#", p_Number];
}
else{
[windValueLabel setText:[NSString stringWithFormat:#"%.2f mph", aFloat / 1.6]];
temperatureLabel.text = [NSString stringWithFormat:#"%#", temperature];
}
When u start the app, its working and showing temperature in fahrenheit, but crashes at celsius man... is that the current conversion. help me out guys

Your formula is slightly off, you want:
CGFloat tempFloat = (tFloat-32.0) / 1.8;
But that's not what making it crash. In fact, it's not crashing for me. What message do you get when it crashes?

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...

Find distance using Local MeasurementSystem in iPhone

I am using the following method to find the distance with MeasurementSystem. Can any one confirm whether it correct way to proceed.
- (NSString *)textForDistance:(CLLocationDistance)meters {
NSString *measureSystem = [[NSLocale currentLocale] objectForKey:NSLocaleMeasurementSystem];
BOOL isMetric = ![measureSystem isEqualToString:#"U.S."];
NSString *distanceString;
if (!isMetric) {
CGFloat feet = meters / METERS_PER_FOOT;
if (feet * 2 > FEET_PER_MILE) {
distanceString = [NSString stringWithFormat:#"%.1f miles", (feet / FEET_PER_MILE)];
} else {
distanceString = [NSString stringWithFormat:#"%.0f feet",feet];
}
} else {
if (meters > 1000) {
distanceString = [NSString stringWithFormat:#"%.1f km", (meters / 1000)];
} else {
distanceString = [NSString stringWithFormat:#"%.0f meters", meters];
}
}
return distanceString;
}
It's a little more natural to use the NSLocaleUsesMetricSystem property rather than the NSLocaleMeasurementSystem property for this:
BOOL isMetric = [[[NSLocale currentLocale] objectForKey:NSLocaleUsesMetricSystem] boolValue];
But either works. This setting is somewhat poorly defined, with lots of "well, if it isn't metric it's probably American" hints in the docs without a clear statement that in fact these are the only options and this is unlikely to change.

iPhone: How do you truncate a float without rounding?

I need to simply truncate a floating point number (truncate and not round it).
float FloatNum = 43.6823921;
NSString *numString = [NSString stringWithFormat:#"%.1f", FloatNum]; // yields 43.7
There are many ways you can do, but your solution is going to depends on a number of factors.
This will always truncate to the tenths place.
float floatNum = 43.6823921;
float truncatedFloat = truncf(floatNum * 10) / 10;
As chown mentioned, you can convert it to a string and take the substring. You might want to use rangeOfString: os something to find the decimal if you don't always deal with double digit numbers.
Another option would be to use NSDecimalNumber with it's method decimalNumberByRoundingAccordingToBehavior: to set rounding explicitly. I've used this option a few times to handle currency manipulations where accuracy is very important.
float num = 43.6894589;
NSDecimalNumber *decimalNumber = [NSDecimalNumber decimalNumberWithDecimal:[[NSNumber numberWithFloat:num] decimalValue]];
float truncatedFloat = [[decimalNumber decimalNumberByRoundingAccordingToBehavior:self] floatValue];
// NSDecimalNumberBehaviors
- (NSDecimalNumber *)exceptionDuringOperation:(SEL)method error:(NSCalculationError)error leftOperand:(NSDecimalNumber *)leftOperand rightOperand:(NSDecimalNumber *)rightOperand {
return [NSDecimalNumber notANumber];
}
- (short)scale {
return 1;
}
- (NSRoundingMode)roundingMode {
return NSRoundDown;
}
This will convert a float to string, get the substring to index 4, the convert back to a float. I think this is the usual way of truncating a float without rounding at all: float myTruncatedFloat = [[[[NSNumber numberWithFloat:43.6823921] stringValue] substringToIndex:4] floatValue];. This will convert 43.6823921 into 43.68.
float myfl = 43.6823921;
NSNumber *num = [NSNumber numberWithFloat:myfl];
NSString *numStr = [num stringValue];
NSLog(#"%#", numStr);
NSLog(#"%#", [numStr substringToIndex:2]);
NSLog(#"%#", [numStr substringToIndex:3]);
NSLog(#"%#", [numStr substringToIndex:4]);
NSLog(#"%#", [numStr substringToIndex:5]);
NSLog(#"%#", [numStr substringToIndex:6]);
NSLog(#"%#", [numStr substringToIndex:7]);
NSLog(#"%#", [numStr substringToIndex:8]);
float newMyFloat = [[numStr substringToIndex:4] floatValue];
NSLog(#"%.1f", newMyFloat);
newMyFloat = [[numStr substringToIndex:5] floatValue];
NSLog(#"%.2f", newMyFloat);
Prints:
[AppDelegate application:didFinishLaunchingWithOptions:]: 43.68239
[AppDelegate application:didFinishLaunchingWithOptions:]: 43
[AppDelegate application:didFinishLaunchingWithOptions:]: 43.
[AppDelegate application:didFinishLaunchingWithOptions:]: 43.6
[AppDelegate application:didFinishLaunchingWithOptions:]: 43.68
[AppDelegate application:didFinishLaunchingWithOptions:]: 43.682
[AppDelegate application:didFinishLaunchingWithOptions:]: 43.6823
[AppDelegate application:didFinishLaunchingWithOptions:]: 43.68239
[AppDelegate application:didFinishLaunchingWithOptions:]: 43.6
[AppDelegate application:didFinishLaunchingWithOptions:]: 43.68

Retrieve UITextfField values and convert to inches with decimal?

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?

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.