Is there a simple string format that will take a decimal representing hours and fractions of hours and show it as hours and minutes?
For example : 5.5 formatted to d
I wrote a few small helper methods for this based on Matt's comment. Might be useful for someone to save you writing it yourself.
/// Converts a decimal e.g. 1.5 to 1 hour 30 minutes
/// The time to convert as a double
///
/// Returns a string in format:
/// x hours x minutes
/// x hours (if there's no minutes)
/// x minutes (if there's no hours)
/// Will also pluralise the words if required e.g. 1 hour or 3 hours
///
public String convertDecimalToHoursMinutes(double time)
{
TimeSpan timespan = TimeSpan.FromHours(time);
int hours = timespan.Hours;
int mins = timespan.Minutes;
// Convert to hours and minutes
String hourString = (hours > 0) ? string.Format("{0} " + pluraliseTime(hours, "hour"), hours) : "";
String minString = (mins > 0) ? string.Format("{0} " + pluraliseTime(mins, "minute"), mins) : "";
// Add a space between the hours and minutes if necessary
return (hours > 0 && mins > 0) ? hourString + " " + minString : hourString + minString;
}
/// Pluralise hour or minutes based on the amount of time
/// The number of hours or minutes
/// The word to pluralise e.g. "hour" or "minute"
/// Returns correct English pluralisation e.g. 3 hours, 1 minute, 0 minutes
public String pluraliseTime(int num, String word)
{
return (num == 0 || num > 1) ? word + "s" : word;
}