I'm working on an Android application that tracks time durations of tasks. Internally, it saves these durations as a float representing how many hours were spent on the task. So 30 minutes would be 0.5, 1 hour would be 1, etc. I've got all that code working great, along with code to convert these into hh:mm format for easier reading.
However, there's also an aspect where the user can manually change this value using a string input box. The following inputs should all be considered valid:
"1:30" => 1.5 "1.83" => 1.83 "0.5" => 0.5
I don't care if users enter something like "0:90", which would be 1.5 hours.
This is my current (untested) solution. Just wondering if there's a better way to go about this:
public static float HoursToFloat(String tmpHours) {
float result = 0;
tmpHours = tmpHours.trim();
// Try converting to float first
try
{
result = Float.parseFloat(tmpHours);
}
catch(NumberFormatException nfe)
{
// OK so that didn't work. Did they use a colon?
if(tmpHours.contains(":"))
{
int hours = 0;
int minutes = 0;
int locationOfColon = tmpHours.indexOf(":");
hours = Integer.parseInt(tmpHours.substring(0, locationOfColon-1));
minutes = Integer.parseInt(tmpHours.substring(locationOfColon+1));
result = hours + minutes*60;
}
}
return result;
}