Convert seconds to fractional hours (half hour being .50 and not 30)
ruby, ruby-on-rails
Solution
Jon is correct, as usual. Just use floating point division:
def hour_quantity
duration / 3600.0
end
When displaying, you might want to round:
puts '%.2f' % hour_quantity
This will give you 2 decimal places, always (e.g. "2.00", "2.25", "2.50"). Alternatively:
puts '%g' % hour_quantity
puts '%g' % 2.0 #=> "2"
puts '%g' % 2.25 #=> "2.25"
puts '%g' % 2.4999999 #=> "2.5"
Problem
I have the following method to convert a duration in seconds to hours. For example, 2 hours and a half would result in 2.30 Also, 2 hours and fifteen minutes would result in 2.15. So it outputs number of hours and number of minutes. I want to modify the method to display 2.5 or 2.25 instead of the above. I need to do it that way to make calculations. For example, if there is a $30/hr salary and employee worked 10 hours and a half, I need to multiply `30*10.5` and not `30*10.30`. ``` def hour_quantity unless self.duration.blank? hours = (self.duration/60)/60 minutes = (self.duration/60) % 60 hours.to_s + '.' + minutes.to_s end end ```