Reputation: 51
I'm using the standard equation of distance / speed = arrival time. This works fine, but the answer is a float number and most people would find it awkward to convert something like 1.75 hrs to be 1 hr and 45 minutes.
I want to take that final float number result and extract the hour(s) separately from the minutes as integers.
Here is what I've tried:
-(IBAction)calculate:(id)sender {
float spd=[speed.text floatValue];
float dist=[distKnots.text floatValue];
//this give me the answer as a float
float arr=(dist/bs);
//this is how I showed it as an answer
//Here I need to convert "arr" and extract the hours & minutes as whole integers
arrivalTime.text=[NSString stringWithFormat:@"%0.02f", arr];
[speed resignFirstResponder];
}
And this is the conversion I tried to do -- and on paper it works, but in code it's full of errors:
int justHours = arr*60;
int justMinutes = (arr*60)-(justHours*60);
//then for the user friendly answer:
arrivalTime.text=[NSString stringWithFormat:@"%n hours and %n minutes", justHours, justMinutes];
I'm new to Objective-C and hoping there is a way to get this to work or a better way altogether to resolve this.
Upvotes: 3
Views: 4183
Reputation: 339816
Your arr
variable is already measured in hours, so you shouldn't be scaling it, just rounding it down:
int justHours = (int)arr;
and then your minutes is sixty times the (integer) difference between the original and rounded hours (i.e. the fractional part).
int justMinutes = (int)((arr - justHours) * 60);
Upvotes: 3
Reputation: 1371
check the NSNumber numberFormater class. I believe you can wrap your float with time format and the return it to the user.
Upvotes: 0
Reputation:
The int justHours = arr/60;
seems to be incorrect, it should be int justHours = arr;
.
Upvotes: 0