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.
Related
This is my Button method. When I press the button it's value is every time increment one & display into Label. Then it's reach 6 then convert like 1.0 , 7 = 1.1, 8 = 1.2 , 12 like 2.0 like cricket over format.
How can I do that?
-(void)OneNoBTNPressedMethod
{
// LBL it's my label & display the text
NSString * overStorage = LBL.text;
// perform the addition operation
CalcOperation operation;
operation = Plus;
//add one every time when we press the button
NSString * overOneBTNStr = [NSString stringWithFormat:#"1"];
NSString *overVal = overOneBTNStr;
LBL.text= [NSString stringWithFormat:#"%qi",[overVal longLongValue]+[overStorage longLongValue]];
}
Thanx in advance..
It worked for me. Hope it works for you as well. Assuming your LBL contains "1" as initial text. hope it helps
- OneNoBTNPressedMethod {
NSString *str = LBL.text;
NSArray *arr = [str componentsSeparatedByString:#"."];
if ([arr count] == 1) {
if ([LBL.text intValue] >= 5) {
LBL.text = [NSString stringWithFormat:#"%i.%i",0,0];
} else {
LBL.text = [NSString stringWithFormat:#"%i",[LBL.text intValue] + 1];
}
} else if ([arr count] == 2) {
if ([[arr objectAtIndex:1] intValue] >= 5) {
int left = [[arr objectAtIndex:0] intValue] + 1;
LBL.text = [NSString stringWithFormat:#"%i.%i",left,0];
} else {
LBL.text = [NSString stringWithFormat:#"%i.%i",[[arr objectAtIndex:0] intValue],[[arr objectAtIndex:1] intValue] + 1];
}
}
}
Try this logic
Let `int num` is count
Then
numBeforeDecimal = num/6;
numAfterDecimal = num%6;
Concatenate both number
[NSString stringWithFormat: #"%d.%d",numBeforeDecimal,numAfterDecimal];
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?
I'm having some issues creating a string using 'initWithFormat'. Here is the code I'm using:
- (void)convertSpeedUnits
{
NSString *speedUnits = [[NSUserDefaults standardUserDefaults] stringForKey:kSpeedUnits];
double speed;
if ([speedUnits isEqualToString:#"Knots"])
{
speed = ms2knots(currentSpeedMS);
}
else if ([speedUnits isEqualToString:#"MPH"])
{
speed = ms2kph(currentSpeedMS);
}
else if ([speedUnits isEqualToString:#"KPH"])
{
speed = ms2mph(currentSpeedMS);
}
NSString *speedLabel = [[NSString alloc] initWithFormat:#"%.2f %s", speed, speedUnits];
currentSpeed.text = speedLabel;
[speedLabel release];
}
I would expect speedLabel to be something like this...
'1.12 Knots' or '1.12 MPH' or '1.12 KPH'
however what I'm getting is the following
'1.12 (null)'
speedUnits is a NSString, so you should use %# and not %s:
NSString *speedLabel = [[NSString alloc] initWithFormat:#"%.2f %#", speed, speedUnits];
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.
How do I format a float to string so that if the user enters a number that has 2 or less decimal places then it is formatted to have 2 decimal places, but if the user enters a float that has 2 or more decimal places then all decimal places are shown. e.g.
4.1 => 4.10
1 => 1.00
1.358484 => 1.358484
So therefore the formatting is to 2 decimal places or more if needed.
Hope I made sense.
Try something like this.
BOOL requiresExtraPrecision (double num) {
double roundedToHundredth = round(num * 100.0) / 100.0;
double diff = num - roundedToHundredth;
if (diff < 0) diff = 0.0 - diff;
if (diff < 0.0000001) {
return NO;
} else {
return YES;
}
}
NSString *formatted (double num) {
if (requiresExtraPrecision(num)) {
return [NSString stringWithFormat:#"%F", num];
} else {
NSNumberFormatter *formatter = [[[NSNumberFormatter alloc] init] autorelease];
[formatter setMaximumFractionDigits:2];
[formatter setMinimumFractionDigits:2];
return [formatter stringFromNumber:[NSNumber numberWithDouble:num]];
}
}
As #Carl wrote in a comment to the question, the hard part is deciding when a double needs all of its precision. In this code, I'm assuming that if the double is "close enough" to a rounded number (within a millionth), then we should just display the rounded number.
You might decide to make it stricter (a billionth?) but you'll always have to use some kind of approximation, because some decimals can't be stored precisely as a float. Even though the user may have typed "0.1" at input time, that information is lost when the number is stored as a float.
So, given that you'll have a float that's extremely close to a decimal but not exactly right, you'll have to decide when you think the float is "close enough" to the decimal.
If you need absolute precision (if you're working with money!) then you should consider using an NSDecimal or an NSDecimalNumber instead of a float.
this could work for you:
NSNumber *aFloat = [NSNumber numberWithFloat:1.2]; //try 1.234 ; 1.23 ; 1.2 ; 1. ; 1
NSString *numberString = [aFloat stringValue];
NSRange dot;
dot = [numberString rangeOfString:#"."];
NSString *finalString;
if (dot.location != NSNotFound) {
NSString *decimals = [numberString substringFromIndex:dot.location + dot.length];
if (decimals.length<1){ // ends with "."
finalString = [numberString stringByAppendingString:#"00"];
}else if (decimals.length<2){ // ends with ".n"
finalString = [numberString stringByAppendingString:#"0"];
}else { // 2 or more decimals: no changes
finalString = numberString;
}
}else { // no decimals
finalString = [numberString stringByAppendingString:#".00"];
}
NSLog(#"______._____finalString:%#", finalString );
EDIT (more flexible, it works with variable numbers of decimals):
NSNumber *aFloat = [NSNumber numberWithFloat:1.1235]; //try 1.234 ; 1.23 ; 1.2 ; 1. ; 1
NSString *numberString = [aFloat stringValue];
NSRange dot;
dot = [numberString rangeOfString:#"."];
if (dot.location == NSNotFound) { // no decimals, add a dot
numberString = [numberString stringByAppendingString:#"."];
NSLog(#"__added dot___ numberString:%#", numberString );
}
dot = [numberString rangeOfString:#"."];
NSString *decimals = [numberString substringFromIndex:dot.location + dot.length];
// int initialDecimals = decimals.length;
int numberOfDecimalsTerget = 2;
for (int initialDecimals = decimals.length; initialDecimals<numberOfDecimalsTerget; initialDecimals++) {
numberString = [numberString stringByAppendingString:#"0"];
}
NSLog(#"__END_._____numberString:%#", numberString );